using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using DICE_GS;

public class AddPathInfo
{
    public int moveCount;
    public int[] addPath;
    public AddPathInfo(int mcount, int[] path)
    {
        moveCount = mcount;
        if (moveCount > 0)
        {
            addPath = new int[moveCount];
            for (int i = 0; i < moveCount; i++)
                addPath[i] = path[i];
        }
    }
}

public enum MoveDir
{
    BottomLeft,
    TopLeft,
    TopRight,
    BottomRight,

};

public struct SidMpPair
{
    public int sid;
    public int mp;
    public SidMpPair(int _sid, int _mp)
    {
        sid = _sid;
        mp = _mp;
    }
}

public class AbnormalState
{
    public AbnormalType abnormalType;
    public EffectReason reason;
    public int relatedSkillId;
    public int abnormalParam;
    public bool isActive;
    public bool isReserve;
    public bool isLastActive;
    public AbnormalState(AbnormalType _enumValue, int _abnormalParam, EffectReason _reason, int _relatedSkillId)
    {
        abnormalType = _enumValue;
        reason = _reason;
        abnormalParam = _abnormalParam;
        relatedSkillId = _relatedSkillId;
        isActive = false;
        isReserve = false;
        isLastActive = false;
    }
    public void Clear()
    {
        isActive = false;
        isReserve = false;
    }

    public void SetLastActive()
    {
        isLastActive = isActive;
    }

    public bool IsSameAbnormal(AbnormalType _ab, int abParam)
    {
        if (abnormalType == _ab && abnormalParam == abParam)
            return true;
        return false;
    }
}

public class ItemGetEffectInfo
{
    public bool isUnit;
    public string itemName;
    public int itemAmount;
    public int boardId;
    public bool isActive;
}

public class BoardPerson : MonoBehaviour
{



    public string nickName;
    public int nLevel;
    public BoardTile curBoardTile;
    public BoardTile crossWayTile;
    public GAME_PAWN_TYPE pawnType;
    public enum MoveState { Still, Moving, WaitMoving };
    public MoveState moveState = MoveState.Still;
    public MoveDir moveDir;
    public bool isMe;
    public bool isBoss;
    public Color myNameTagColor;
    EffectManager effectMgr;

    tk2dSpriteAnimator anim;
    tk2dSprite sprite;
    PathManager pathManager;
    public BoardTile curPassingBoard;

    Queue<int> moveToBoardList = new Queue<int>();
    public int nSkipTileCountByAvoid;
    public bool bChasing;
    public int chaseStartBoardID;
    public bool bCanCombatRoll = false;
    public int mSID;
    public int order;
    float moveSpeed = 1.0f;
    float originalMoveSpeed;
    List<BoardTile> mTargetBoard = new List<BoardTile>();

    Vector3 destinationBoardPos = new Vector3();
    Vector3 moveStartBoardPos = new Vector3();
    float destBoardDist;
    public int mypath;
    public bool isAboutTeleport;
    public int teleportBoardID;
    //	public int teleportBoardID_afterCombat;
    public bool isMoveBufActivated;
    public bool isWaitingSelectPath;
    public ParticleSystem psMoveBuf;
    public bool isForwardMoving;
    //	public bool isMoveBufActive;
    public List<int> selectPathBoardID = new List<int>();
    public Queue<AddPathInfo> addPathQueue = new Queue<AddPathInfo>();
    public Queue<AddPathInfo> afterTeleportPathQueue = new Queue<AddPathInfo>();
    public List<CSkillData> skillList;
    public int totalMoveCount;
    public int remainMoveCount;
    public int nCurTurn;
    public bool isToBeBound;
    public BoardPerson togetherTeleportPerson;
    public int avoidTargetSID;
    public List<int> avoidTargetList = new List<int>();
    public bool bShowItemGetEffect;
    public bool bShowItemGetEffect_fromNPC;
    public string itemNameToGet;
    public bool itemNameToGet_isUnit;
    public int itemAmountToGet;
    public bool bWaitForExtraTurn;
    public DateTime battleDeadLine;
    public DateTime selectPathDeadLine;
    public DateTime directionRollDeadLine;
    public bool bWaitCombatRoll_attacker;
    public bool bWaitCombatRoll_defender;
    public bool bWaitDirectionRoll;
    public bool bWaitDirectionRollUI;
    public bool bWaitActivateDiceOverHead;
    public bool bWaitActivateDiceOverHead_aibattle;
    public bool isTeleportDoing;
    public bool isToChangeBoardStatus;
    public int boardIdToChange;
    public int boardHeightToChange;
    public int boardDataTypeToChange;
    ChangeBoardReason boardChangeReason;
    public bool bShowMyTurnAlarm;
    public int m_myTurn;
    public string idleBackAnimName;
    public string idleFrontAnimName;
    public string backRunAnimName;
    public string frontRunAnimName;
    public string backAttackAnimName;
    public string frontAttackAnimName;
    public string backDamageAnimName;
    public string backExpelledAnimName;
    public string backExpelledGetupAnimName;
    public string frontExpelledAnimName;
    public string frontExpelledGetupAnimName;
    public string frontDamageAnimName;
    public string backSkillCastAnimName;
    public string frontSkillCastAnimName;
    //public string backVictoryAnimName;
    public string victoryAnimName;
    public string dicehitAnimName;

    public static float upOffset = 0.2018337f;
    public BoardTile opponentOnTile;
    public bool bMovedToBattlePosition;
    //public bool bFaceToBattleOpponent;
    public bool isAboutToDelete;
    public bool isBattleWinner;
    public BoardPerson battleOpponent;
    public bool bGlowDestinationTile;
    public bool isBackExpelled;
    public bool bBackExpellInitiated;
    public float backExpellInitSpeed;
    public bool bCastedSkill;
    public TagPerson tagPerson;
    public bool isRetired;
    public GameObject groundTag;
    public GameObject tagOverHead;
    public int gameOrder;
    public int charID;
    public string char_name;
    public bool bUsedHPRestoreEffect;
    public bool bContinueFromRetire;
    public GameObject shadow;
    //public GameObject groundTag;

    public bool bActivateDiceOverHead;


    public bool bAttackEventTriggered;
    public bool isDamagedAnimCompleted;
    public bool bDiceHitTriggered;
    public int[] nDice;
    public bool isDirectionDice;
    public bool isFalling;
    public float overHeadNameTagOffset;
    public float overHeadDiceOffset;
    public float overHeadDiceNumOffset;
    public bool bUseSkill_ShuffleDeck;
    public bool bUseSkill_ForceNextCard;
    public bool bUseSkill_CardToTomb;
    public bool bUseSkill_CardResurrect;
    public bool bUseSkill_BackMove;
    public bool bUseSkill_TileLift;
    public float timeTileLift;
    public bool bUseSkill_TileFrozen;
    public bool damageAnimationPlayed;

    public GameObject tomb;
    int victoryAnimRepeat;
    public bool isTrapDecoy;
    public bool isBumpyMoving;

    public int createFootSmokeCount;
    public static GameObject teleportTempObj;

    //GameObject manaRecoverEff;
    //ParticleSystem manaRecoverEffPS;
    public bool isJumping;
    float z_to_apply;
    public Transform mytrans;
    public bool isChaseMoving;
    public int m_lapcount = -1;
    List<int> modifiedTargetBoardIds = new List<int>();
    public float moveSpeedManual;

    public bool isWaitingBattleDiceList;
    public bool bWaitForVictoryGame;
    public int myFinalRank;
    public GameObject skillIconOverHead;
    public bool isLapChanged;
    //public bool abnormalSealActiveCard;
	ItemGetEffectInfo m_bonusLootInfo;
	public bool m_isBonusLootEffectDoing;
    List<ItemGetEffectInfo> itemGetEffectByPassBoard = new List<ItemGetEffectInfo>();
    List<AbnormalState> abnormalSateList = new List<AbnormalState>();
    List<AbnormalState> cardAbnormalList = new List<AbnormalState>();
    public PC_OP_CHANGE_ABNORMAL_EFFECT abnormalPacket;
	public PC_OP_UNIT_ACTIVATION_INFO unitActivationPacketByBoard;
    public int AIPresetId = -1;
    public static Dictionary<int, GameObject> swordTrailPrefabDic_back = new Dictionary<int, GameObject>();
    public static Dictionary<int, GameObject> swordTrailPrefabDic_front = new Dictionary<int, GameObject>();
    GameObject swordTrailFront;
    GameObject swordTrailBack;
    bool isMoveFromStartFirstTime;
    static GameObject shieldPrefab;
    //static List<GameObject> shieldObjList = new List<GameObject>();
    static GameObject m_shieldGo;
    public bool isPushBackResistActivated;
    bool spriteFlipXReserved;
    public int m_achieveTempSkillId;
    static List<bool> bShowMovingCourseDone = new List<bool>();
    bool isLapCountGoingToZero;

    void Awake()
    {
        //pathManager = GameObject.FindWithTag("Path Manager").GetComponent<PathManager>();
        //upOffset = renderer.bounds.extents.y;

        //upOffset = 0.206981f;

        //upOffset = 0.2018337f;

        //if(BoardManager.Instance.elementType == element.sky)
        //	upOffset -= 0.102006f;

        mytrans = gameObject.transform;
    }


    PathManager GetPathManager()
    {
        if (pathManager == null)
        {
            pathManager = GameObject.FindWithTag("Path Manager").GetComponent<PathManager>();
        }
        return pathManager;
    }


    // Use this for initialization
    void Start()
    {


        //DetermineAnimation(0,0);		
    }

    public void PreUpdateAbnormalState()
    {
        foreach (AbnormalState abState in cardAbnormalList)
        {
            abState.isActive = false;
        }

        foreach (AbnormalState ab in abnormalSateList)
        {
            ab.SetLastActive();
            ab.Clear();
        }
    }

    public void AfterUpdateAbnormalState()
    {
        foreach (AbnormalState ab in abnormalSateList)
        {
            if (ab.isLastActive && !ab.isActive)
                HudManager.Instance.ShowBuffIcon(false, SID, ab.abnormalType, ab.abnormalParam, ab.relatedSkillId);
        }
        HudManager.Instance.RearrangeBufIcon(SID);
    }

    //	public void ClearAbnormalState()
    //	{
    //		foreach( AbnormalState ab in abnormalSateList)
    //		{
    //			ab.Clear();
    //			HudManager.Instance.ShowBuffIcon(false, SID, AbnormalType.NONE);
    //		}
    //	}

    public bool IsAbnormalStateRelatedSkill(AbnormalType abnormalType, int skillId)
    {
        foreach (AbnormalState ab in abnormalSateList)
        {
            if (ab.abnormalType == abnormalType && ab.isActive && ab.relatedSkillId == skillId)
                return true;
        }
        return false;
    }

    public bool IsAbnormalState(AbnormalType abnormalType)
    {
        foreach (AbnormalState ab in abnormalSateList)
        {
            if (ab.abnormalType == abnormalType && ab.isActive)
                return true;
        }
        return false;
    }

    public int GetAbnormalParam(AbnormalType abnormalType)
    {
        foreach (AbnormalState ab in abnormalSateList)
        {
            if (ab.abnormalType == abnormalType && ab.isActive)
                return ab.abnormalParam;
        }
        return 0;
    }

    public bool IsAbnormalState(AbnormalType abnormalType, int abParam)
    {
        foreach (AbnormalState ab in abnormalSateList)
        {
            if (ab.isActive && ab.abnormalType == abnormalType && ab.abnormalParam == abParam)
                return true;
        }
        return false;
    }

    bool HasCardAbnormal(AbnormalType abType, int skillId)
    {
        foreach (AbnormalState abState in cardAbnormalList)
        {
            if (abState.isActive && abState.abnormalType == abType && abState.relatedSkillId == skillId)
                return true;
        }
        return false;
    }

    bool HasCardAbnormal(AbnormalType abType)
    {
        foreach (AbnormalState abState in cardAbnormalList)
        {
            if (abState.isActive && abState.abnormalType == abType)
                return true;
        }
        return false;
    }

    void AddCardAbnormal(AbnormalType abnormalType, int abnormalParam, int relatedSkillId)
    {
        foreach (AbnormalState abState in cardAbnormalList)
        {
            if (!abState.isActive)
            {
                abState.isActive = true;
                abState.abnormalType = abnormalType;
                abState.abnormalParam = abnormalParam;
                abState.relatedSkillId = relatedSkillId;
                return;
            }
        }
        AbnormalState newState = new AbnormalState(abnormalType, abnormalParam, EffectReason.UNIT, relatedSkillId);
        newState.isActive = true;
        cardAbnormalList.Add(newState);
    }

    public void SetAbnormal(AbnormalType abnormalType, int abnormalParam, int duration, EffectReason abnormalReason, int relatedSkillId)
    {
        if (abnormalReason == EffectReason.UNIT)
        {
            if (!HasCardAbnormal(abnormalType, relatedSkillId))
                AddCardAbnormal(abnormalType, abnormalParam, relatedSkillId);
            return;
        }
        AbnormalState abnormalState = null;
        foreach (AbnormalState ab in abnormalSateList)
        {
            if (ab.IsSameAbnormal(abnormalType, abnormalParam))
            {
                if (ab.isLastActive)
                {
                    ab.isActive = true;
                    glog.debug(abnormalType + "  isLastactive  ... skip  ");
                    return;
                }
                glog.debug("find in list   " + abnormalType.ToString() + "  " + abnormalParam);
                abnormalState = ab;
                break;
            }
        }
        if (abnormalState == null)
        {
            abnormalState = new AbnormalState(abnormalType, abnormalParam, abnormalReason, relatedSkillId);
            abnormalSateList.Add(abnormalState);
        }

        //		if(IsMovingOrWaitMoving())
        //			abnormalState.isReserve = true;
        //		else
        //		{
        DoAbnormal(abnormalState);
        //		}
    }

    void DoAbnormal(AbnormalState abnormalState)
    {
        abnormalState.isReserve = false;
        abnormalState.isActive = true;
        if (abnormalState.reason == EffectReason.SKILL)
            HudManager.Instance.ShowBuffIcon(true, SID, abnormalState.abnormalType, abnormalState.abnormalParam, abnormalState.relatedSkillId);
        if (abnormalState.abnormalType == AbnormalType.BIND)
        {
            ShowBindEffect();
        }
        else if (abnormalState.abnormalType == AbnormalType.ELEMENT_CHANGE && abnormalState.abnormalParam == (int)element.absolute)
        {
            //CardManager.Instance.ElementChangeAbsolute(SID);
        }
        else if (abnormalState.abnormalType == AbnormalType.MODIFY_MOVE_COST)
        {
            //SkillManager.Instance.AddSkillEffect(this, 100034);
            SkillManager.Instance.AddSkillEffect(this, abnormalState.relatedSkillId);
        }
        //		else if(abnormalState.abnormalType==AbnormalType.DAMAGE_REDUCE)
        //		{
        //			SkillManager.Instance.AddSkillEffect(this, 100037);
        //		}
        //		else if(abnormalState.abnormalType==AbnormalType.DAMAGE_REFLECT)
        //		{
        //			SkillManager.Instance.AddSkillEffect(this, 100029);
        //		}
        //		else if(abnormalState.abnormalType==AbnormalType.DAMAGE_INCREASE)
        //		{
        //			SkillManager.Instance.AddSkillEffect(this, 500018);
        //		}
    }

    public void CheckAbnormalReserve()
    {
        /*
        foreach( AbnormalState ab in abnormalSateList)
        {
            if(ab.isReserve)
                DoAbnormal(ab);
        }*/
        if (abnormalPacket != null)
        {
            StageManagerWrapper.manager.UpdateAbnormalState(this, abnormalPacket);
            abnormalPacket = null;
        }
    }

    public void ShowBindEffect()
    {
        CardManager.Instance.ShowSkillNameEffect(CStringTableManager.Instance.GetItemById(1666), transform);
        ShowBoundObject();
        HudManager.Instance.ChangeFace(SID, false);
        if (isMe)
            UIManager.Instance.ShowSkillInfo(CStringTableManager.Instance.GetItemById(1698), false);
    }

    public void InitAnimation(int nIndexCollection)
    {
        float defaultOverHeadNameTagOffset = IngameSetting.Instance.charTagOffset[0];

        if (nIndexCollection == 1)
        {
            if (char_name.StartsWith("b"))
            {
                overHeadNameTagOffset = defaultOverHeadNameTagOffset + 0.0723112f;
                overHeadDiceOffset = 0.519207f;
                overHeadDiceNumOffset = 0.6070719f;
            }
            else
            {
                overHeadNameTagOffset = defaultOverHeadNameTagOffset - 0.05f;
                overHeadDiceOffset = 0.3990607f;
                overHeadDiceNumOffset = 0.506022f;
            }
        }
        else
        {
            if (!swordTrailPrefabDic_back.ContainsKey(charID))
            {
                Debug.LogError("swordTrailPrefabDic added key  for charID=" + charID);
                swordTrailPrefabDic_back.Add(charID, null);
                swordTrailPrefabDic_front.Add(charID, null);
            }
            if (charID == 1)//dawool
            {
                overHeadDiceOffset = 0.519207f;
                overHeadDiceNumOffset = 0.6070719f;
            }
            else if (charID == 2) // issad
            {
                overHeadDiceOffset = 0.3990607f;
                overHeadDiceNumOffset = 0.506022f;
                //upOffset += 0.0037f;
            }
            else if (charID == 3)  //mana
            {
                overHeadDiceOffset = 0.3990607f;
                overHeadDiceNumOffset = 0.506022f;
            }
            else if (charID == 4) //teharil
            {
                overHeadDiceOffset = 0.4303184f;
                overHeadDiceNumOffset = 0.5283489f;
            }
            else if (charID == 5)
            {
                overHeadDiceOffset = 0.4303184f;
                overHeadDiceNumOffset = 0.5283489f;
                //upOffset += 0.017971f;
            }
            else
            {
                overHeadDiceOffset = 0.4303184f;
                overHeadDiceNumOffset = 0.5283489f;
            }
            overHeadNameTagOffset = defaultOverHeadNameTagOffset + IngameSetting.Instance.GetCharOffset(charID);
            char_name = charID.ToString("00");
        }



        glog.debug("char_name=" + char_name);
        dicehitAnimName = char_name + "_roll_a_front";
        backSkillCastAnimName = char_name + "_skill_cast_a_back";
        frontSkillCastAnimName = char_name + "_skill_cast_a_front";
        victoryAnimName = char_name + "_victory_a_front";
        backExpelledAnimName = char_name + "_expelled_a_back";
        backExpelledGetupAnimName = char_name + "_expelled_b_back";
        frontExpelledAnimName = char_name + "_expelled_a_front";
        frontExpelledGetupAnimName = char_name + "_expelled_b_front";
        backDamageAnimName = char_name + "_demaged_a_back";
        frontDamageAnimName = char_name + "_demaged_a_front";
        backAttackAnimName = char_name + "_attack_a_back";
        frontAttackAnimName = char_name + "_attack_a_front";
        backRunAnimName = char_name + "_run_a_back";
        frontRunAnimName = char_name + "_run_a_front";
        idleBackAnimName = char_name + "_idle_a_back";
        idleFrontAnimName = char_name + "_idle_a_front";

        if (nIndexCollection == 1 && !char_name.StartsWith("b"))
        {
            backRunAnimName = idleBackAnimName;
            frontRunAnimName = idleFrontAnimName;
        }

        sprite = gameObject.GetComponent<tk2dSprite>();

        GameObject tmp = Resources.Load("Prefabs/Char/" + char_name) as GameObject;
        sprite.SetSprite(tmp.GetComponent<CharManager>().collection, char_name + "IdAF0000");
        //float scaleMod = 0.1f;//0.117647059f; // for 0.85
        //sprite.scale = new Vector3(scaleMod,scaleMod,scaleMod); 
        //sprite.renderer.sortingLayerID = -1;
        anim = gameObject.AddComponent<tk2dSpriteAnimator>();
        anim.Library = tmp.GetComponent<CharManager>().animationLib;


        PlayAnim(idleBackAnimName);
        anim.AnimationEventTriggered = this.AnimEventCallBack;
        anim.AnimationCompleted = this.AnimCompleteCallBack;
    }

    public void InitAnimForNPC()
    {
        InitAnimation(1);
        DeterminAnimFromCurTile(!isBoss);
        anim.PlayFrom(UnityEngine.Random.Range(0.0f, 1.0f));
    }

    //	IEnumerator CoInitAnimForNPC()
    //	{
    //		yield return new WaitForSeconds( Random.Range(0.0f, 1.0f) );
    //		DeterminAnimFromCurTile(!isBoss);
    //	}

    public int SID
    {
        get { return mSID; }
        set { mSID = value; }
    }

    public void SetInitialCurrentBoard(BoardTile tile, bool bDetermineAnim, int nTotalPlayerCount)
    {
        curBoardTile = tile;
        curPassingBoard = tile;
        curBoardTile.personOn.Add(this);
        ReCalculateZ(false);
        if (tile.boardInfo.isStart && CSceneManager.gameStatus != GameStatus.GS_PLAYING && BoardManager.Instance.curMapRaceType != RaceType.COMBAT_RUN)
        {
            isMoveFromStartFirstTime = true;
            Vector3 newPos = tile.GetPlayerPos(nTotalPlayerCount);
            newPos.z = BoardManager.CalcPlayerZFromTile_Start(tile.transform.position.z, nTotalPlayerCount);
            z_to_apply = newPos.z;
            mytrans.position = newPos;
        }
        else
            mytrans.position = GetTilePlayerPos(curPassingBoard, false);
        CheckCurPassingBoard(true);
        if (bDetermineAnim)
            DeterminAnimFromCurTile(false);
    }

    public void MoveToAttackerPos()
    {
        SoundManager.Instance.PlaySound(0);
        opponentOnTile = curBoardTile;
        Vector3 newPos = GetTilePlayerPos(curBoardTile, true);
        iTween.MoveTo(gameObject, iTween.Hash("position", newPos, "easetype", "linear", "onupdate", "MoveUpdate", "time", 0.2f));
    }

    Vector3 GetTilePlayerPos(BoardTile tile, bool bCheckBattlePos)
    {
        //Vector3 newPos = tile.transform.position;//tile.collider.bounds.center;
        //newPos.y += 0.05f;

        Vector3 newPos = tile.GetPlayerPos();

        if (tile.boardInfo.isStart)
            bCheckBattlePos = false;

        if (bCheckBattlePos)
        {
            glog.debug(SID + "  GetTilePlayerPos checkBattlePos " + tile.boardInfo.id + "  " + tile.personOn.Count);
            if (opponentOnTile != null)
                glog.debug("opponentOnTile.boardInfo.id " + opponentOnTile.boardInfo.id);
        }

        if (/*!tile.boardInfo.isGoal && */tile == opponentOnTile && bCheckBattlePos && tile.personOn.Count > 0 && battleOpponent != null)
        {
            if (tile.personOn.Contains(battleOpponent) && !battleOpponent.isRetired)
            {
                Vector2 offsetvec = GetBattleOffset(moveDir);
                glog.debug("get battle pos modify " + offsetvec.x + "  " + offsetvec.y + "  " + newPos.x + "  " + newPos.y);
                newPos.x += offsetvec.x;
                newPos.y += offsetvec.y;
                bMovedToBattlePosition = true;
                //bFaceToBattleOpponent = true;
                opponentOnTile = null;
                battleOpponent.MoveToBattlePosition(moveDir);
            }
        }

        //newPos.y += upOffset;	
        newPos.z = z_to_apply;
        return newPos;
    }

    public void MoveToBattlePosition(MoveDir _dir)
    {
        glog.debug(SID + "  move to battle pos " + bMovedToBattlePosition);
        if (bMovedToBattlePosition)
        {
            Debug.LogError("already moved to battle position");
            return;
        }
        if (isFalling)
        {
            Debug.LogError("is falling... skip");
            return;
        }
        SetMoveDir(_dir);

        //Vector3 newPos = curBoardTile.transform.position;//tile.collider.bounds.center;
        //newPos.y += 0.05f;
        Vector3 newPos = curBoardTile.GetPlayerPos();
        Vector2 offsetvec = -GetBattleOffset(moveDir);
        newPos.x += offsetvec.x;
        newPos.y += offsetvec.y;
        bMovedToBattlePosition = true;
        //bFaceToBattleOpponent = false;
        //newPos.y += upOffset;	
        newPos.z = mytrans.position.z;
        DetermineAnimation(1, 1, 1);
        iTween.MoveTo(gameObject, iTween.Hash("position", newPos, "easetype", "linear", "oncomplete", "FaceToOpponent", "onupdate", "MoveUpdate", "time", 0.2f));
    }

    void FaceToOpponent()
    {
        SetMoveDir(GetFaceToDir(moveDir));
        glog.debug(SID + " FaceToOpponent compelte " + moveDir);
        //bFaceToBattleOpponent = true;
        DetermineAnimation(0, 0, 0);
    }

    Vector2 GetBattleOffset(MoveDir _dir)
    {
        float offset_battlepos_x = 0.10f;
        float offset_battlepos_y = 0.05f;
        if (_dir == MoveDir.TopRight)
        {
            offset_battlepos_x = -offset_battlepos_x;
            offset_battlepos_y = -offset_battlepos_y;
        }
        else if (_dir == MoveDir.TopLeft)
            offset_battlepos_y = -offset_battlepos_y;
        else if (_dir == MoveDir.BottomRight)
            offset_battlepos_x = -offset_battlepos_x;
        return new Vector2(offset_battlepos_x, offset_battlepos_y);
    }

    //	Vector2 GetBattleOffset_defender(MoveDir _dir)
    //	{
    //		return -GetBattleOffset_attacker(_dir);
    //	}

    MoveDir GetFaceToDir(MoveDir _dir)
    {
        if (_dir == MoveDir.TopRight)
            return MoveDir.BottomLeft;
        else if (_dir == MoveDir.BottomLeft)
            return MoveDir.TopRight;
        else if (_dir == MoveDir.BottomRight)
            return MoveDir.TopLeft;
        else// if(_dir == MoveDir.TopLeft)
            return MoveDir.BottomRight;
    }

    public void MoveToTileCenter()
    {
        StartCoroutine("CoMoveToTileCenter");
    }

    IEnumerator CoMoveToTileCenter()
    {
        yield return new WaitForSeconds(0.3f);
        glog.debug(SID + " move to tile center " + curBoardTile.boardInfo.id);
        DetermineAnimation(1, 1, 1);
        iTween.MoveTo(gameObject, iTween.Hash("position", GetTilePlayerPos(curBoardTile, false), "easetype", "linear", "oncomplete", "ArriveTileCenter", "onupdate", "MoveUpdate", "speed", 1));
    }

    void ArriveTileCenter()
    {
        bMovedToBattlePosition = false;
        //		if(charID==1)
        //		{
        //			ForceMoveDirFront();
        //			AnimPlayByDir(backVictoryAnimName, frontVictoryAnimName);
        //			if(charID==1)
        //			{
        //				BoardManager.Instance.RestartFSM(gameObject, "jumping");
        //				StartCoroutine(StopFSM("jumping",0.9f) );
        //			}
        //			StartCoroutine(BackToIdleAnim(0.9f));
        //		}
        //		else
        //		{
        PlayVictoryAnim(0);
        //anim.AnimationCompleted = this.VictoryAnimCompleted;
        //		}
    }

    public void PlayVictoryAnim(int repeat)
    {
        HudManager.Instance.ChangeFace(SID, true);
        victoryAnimRepeat = repeat;
        //if(repeat==0)
        //	HudManager.Instance.ShowEmotionChat(SID, "combat_win");
        if (repeat == 2)
        {
            if (isMe)
                SoundManager.Instance.PlaySound(ESound.Voice_GoalWin_01);
            HudManager.Instance.ShowAIEmotionChat(SID, "rank_01");
            foreach (BoardPerson person in BoardManager.Instance.boardPersonPCList)
            {
                if (person == this)
                    continue;
                if (person.isMe)
                    SoundManager.Instance.PlaySound(ESound.Voice_GoalLose_02);
                HudManager.Instance.ShowAIEmotionChat(person.SID, "rank_0" + person.myFinalRank.ToString());
            }
        }
        PlayAnim(victoryAnimName);
        SetToDefaultAnimFps(victoryAnimName);
    }

    void CheckItemGetEffect()
    {
        if (bShowItemGetEffect)
        {
            //HudManager.Instance.ShowEmotionChat(SID,"skill_good");
            bShowItemGetEffect = false;
            MainHUDUI.Instance.ShowItemGetEffect(itemNameToGet_isUnit, this, itemNameToGet, itemAmountToGet, true);
        }
    }

    public void CheckItemGetEffectByNPC(BoardPerson person)
    {
        Debug.Log("CheckItemGetEffectByNPC");
        if (bShowItemGetEffect_fromNPC)
        {
            bShowItemGetEffect_fromNPC = false;

            MainHUDUI.Instance.ShowItemGetEffect(itemNameToGet_isUnit, person, itemNameToGet, itemAmountToGet, true);
        }
    }

	public void CheckBonusLoot(BoardPerson person)
	{
		if(m_bonusLootInfo!=null)
		{
			Debug.LogError("Bonus Loot");
			Invoke ("BonusLootEffDone",2.0f);
			EffectManager.Instance.CreateBonusLootEff(person);
			HudManager.Instance.ShowAIEmotionChat(SID, "skill_good");
			MainHUDUI.Instance.ShowItemGetEffect(m_bonusLootInfo.isUnit, person, m_bonusLootInfo.itemName, m_bonusLootInfo.itemAmount, true);
			m_bonusLootInfo=null;
		}
	}

	void BonusLootEffDone()
	{
		m_isBonusLootEffectDoing=false;
	}

    void CheckItemGetEffectByPassingBoard(int bid)
    {
        foreach (ItemGetEffectInfo eInfo in itemGetEffectByPassBoard)
        {
            if (eInfo.isActive && eInfo.boardId == bid)
            {
                MainHUDUI.Instance.ShowItemGetEffect(eInfo.isUnit, this, eInfo.itemName, eInfo.itemAmount, false);
                eInfo.isActive = false;
                break;
            }
        }
    }


    IEnumerator StopFSM(string fsmName, float delay)
    {
        yield return new WaitForSeconds(delay);
        BoardManager.Instance.StopFSM(gameObject, fsmName);
    }

    IEnumerator BackToIdleAnim(float delay)
    {
        yield return new WaitForSeconds(delay);
        DetermineAnimation(0, 0, 0);
    }

    public void PlaySkillCastAnim(int skillId, CSkillData skillData, bool bUseBuffEffect, bool bCameraToTarget, BoardPerson targetPerson, bool isEnemyAll)
    {
        if (!BoardManager.Instance.bWaitForUIBattleDice)
        {
            int dx = GetPathManager().GetBoardTile(curBoardTile.boardInfo.pathInfo[mypath].forwardBoards[0]).boardInfo.index_x - curBoardTile.boardInfo.index_x;
            int dy = GetPathManager().GetBoardTile(curBoardTile.boardInfo.pathInfo[mypath].forwardBoards[0]).boardInfo.index_y - curBoardTile.boardInfo.index_y;
            FindMoveDir(dx, dy);
        }

        AnimPlayByDir(backSkillCastAnimName, frontSkillCastAnimName);

        //anim.AnimationCompleted = this.SkillAnimCompleted;
        if (skillId == 100025)
            SoundManager.Instance.PlaySound(ESound.Skill_Confuse_Bind_Cast);
        else
            SoundManager.Instance.PlaySound(10);

        BoardManager.Instance.HideDiceTemporarily(true);
        HideTagOverHead(true);
        bCastedSkill = true;

        if (!bCameraToTarget) // if cast to me skill
        {
            SkillManager.Instance.AddSkillEffect(this, skillId);
        }

        StartCoroutine(CoWaitSkillShow(bUseBuffEffect, skillId, skillData, bCameraToTarget, targetPerson, isEnemyAll));
    }

    IEnumerator CoWaitSkillShow(bool bUseBuffEffect, int skillId, CSkillData skillData, bool bCameraToTarget, BoardPerson targetPerson, bool isEnemyAll)
    {
        yield return new WaitForSeconds(1.0f);

        if (!bCameraToTarget)
        {
            if(skillData.emotion_feeling=="good")
            	HudManager.Instance.ShowAIEmotionChat(SID, "skill_good");

            BoardManager.Instance.bWaitForSkillShow = false;
            if (bUseBuffEffect)
            {
                EffectManager.Instance.PlayEffectParent(9, transform);
                EffectManager.Instance.DisableParticle(9, 2.0f);
            }
            float waitTime = SkillManager.Instance.waitSkillEffectClearTime(skillId);
            if (waitTime - 1.0f > 0)
                yield return new WaitForSeconds(waitTime - 1.0f);
        }
        else
        {
			if(skillData.emotion_feeling=="bad")
				HudManager.Instance.ShowAIEmotionChat(targetPerson.SID, "skill_bad");

            if (!isEnemyAll && targetPerson.isMe)
            {
                SoundManager.Instance.PlaySound(ESound.Voice_Skill_01);
                if (skillData.notify_string != "")
                {
                    string strText = CStringTableManager.Instance.GetItemByName(skillData.notify_string);
                    UIManager.Instance.ShowSkillInfo(strText, false);
                }

            }
            if (isEnemyAll)
            {
                foreach (BoardPerson person in BoardManager.Instance.boardPersonPCList)
                {
                    if (this != person && !person.isRetired) // in case enemy all , cast all person except caster
                    {
                        if (person.isMe)
                            SoundManager.Instance.PlaySound(ESound.Voice_Skill_01);
                        HudManager.Instance.ChangeFace(person.SID, false);
                        MainHUDUI.Instance.ShowSkillIconEffect(person, skillData.icon_name);

                        EffectManager.Instance.PlayEffect_Debuf(targetPerson);
                        SkillManager.Instance.AddSkillEffect(person, skillId);
                        if (skillId == 100025)
                            SoundManager.Instance.PlaySound(ESound.Skill_Confuse_Bind_Debuff);
                        else
                            SoundManager.Instance.PlaySound(ESound.Skill_Done);
                        StageManagerWrapper.camControl.SetCameraFocus(person.transform);
                        yield return new WaitForSeconds(1.0f);
                    }
                }
            }
            else
            {
                bool isBindReflected = false;
                if (skillId == 100025 && targetPerson.HasCardAbnormal(AbnormalType.REFLECT_EFFECT, 502123))// if card_ignore_bind_03
                    isBindReflected = true;
                if (!isBindReflected)
                    HudManager.Instance.ChangeFace(targetPerson.SID, false);
                MainHUDUI.Instance.ShowSkillIconEffect(targetPerson, skillData.icon_name);
                if (skillId == 100042)//mp_burn
                { }
                else
                {
                    if (isBindReflected)
                        EffectManager.Instance.PlayEffect_SkillReflect(targetPerson);
                    else
                        EffectManager.Instance.PlayEffect_Debuf(targetPerson);
                }

                SkillManager.Instance.AddSkillEffect(targetPerson, skillId);
                if (skillId == 100025 && !isBindReflected)//bind
                    SoundManager.Instance.PlaySound(ESound.Skill_Confuse_Bind_Debuff);
                else
                    SoundManager.Instance.PlaySound(ESound.Skill_Done);

                StageManagerWrapper.camControl.SetCameraFocus(targetPerson.transform);
                if (skillId == 100028)
                {// banana slip skill. force back expell
                    targetPerson.isBackExpelled = true;
                    yield return new WaitForSeconds(0.8f);
                    BoardManager.Instance.bWaitForSkillShow = false;
                    yield return new WaitForSeconds(1.2f);
                }
                else
                    yield return new WaitForSeconds(1.0f);
            }

            BoardManager.Instance.bWaitForSkillShow = false;
            StageManagerWrapper.camControl.SetCameraFocus(transform);
        }

        BoardManager.Instance.HideDiceTemporarily(false);
        HideTagOverHead(false);
        //		if(BoardManager.Instance.bWaitForUIBattleDice)
        //		{
        //			if(BoardManager.Instance.boardPerson_me == this)
        //			{
        //				UIManager.Instance.ShowUIBattleRoll(true, StageManagerWrapper.combatRollDeadLine, DiceShapeType.Defender);
        //			}
        //		}
        BoardManager.Instance.bWaitForUIBattleDice = false;
    }

    void HideTagOverHead(bool bHide)
    {
        if (tagOverHead != null)
            tagOverHead.SetActive(!bHide);
    }

    public void DeterminAnimFromCurTile(bool isOpposite)
    {
        if (curBoardTile.boardInfo.pathInfo[mypath].forwardBoards.Count > 0)
        {
            int dx = GetPathManager().GetBoardTile(curBoardTile.boardInfo.pathInfo[mypath].forwardBoards[0]).boardInfo.index_x - curBoardTile.boardInfo.index_x;
            int dy = GetPathManager().GetBoardTile(curBoardTile.boardInfo.pathInfo[mypath].forwardBoards[0]).boardInfo.index_y - curBoardTile.boardInfo.index_y;
            if (isOpposite)
            {
                dx = -dx;
                dy = -dy;
            }
            FindMoveDir(dx, dy);
        }
        else if (curBoardTile.boardInfo.pathInfo[mypath].backBoards.Count > 0)
        {
            int dx = GetPathManager().GetBoardTile(curBoardTile.boardInfo.pathInfo[mypath].backBoards[0]).boardInfo.index_x - curBoardTile.boardInfo.index_x;
            int dy = GetPathManager().GetBoardTile(curBoardTile.boardInfo.pathInfo[mypath].backBoards[0]).boardInfo.index_y - curBoardTile.boardInfo.index_y;
            if (isOpposite)
            {
                dx = -dx;
                dy = -dy;
            }
            FindMoveDir(dx, dy);
        }
        DetermineAnimation(0, 0, 0);
    }

    public void SetCombatOpponent(bool _isWinner, BoardPerson opponent)
    {
        isBattleWinner = _isWinner;
        SetCombatInfo(opponent);
    }

    public void SetCombatInfo(BoardPerson opponent)
    {
        glog.debug("SetCombatInfo opponent=" + opponent.SID);
        battleOpponent = opponent;
        opponent.battleOpponent = this;
        if (opponent.curBoardTile == null)
        {
            Debug.LogError("opponent curboardtile null");
            opponentOnTile = null;
        }
        else
        {
            opponentOnTile = opponent.curBoardTile;
        }
    }

    void StopMoving(bool isMoveCountZero)
    {
        glog.debug(SID + "  ==StopMoving " + nickName + "  ratioToGoal=" + curBoardTile.boardInfo.pathInfo[mypath].ratioToGoal + "  addPath=" + addPathQueue.Count + "  bid=" + curBoardTile.boardInfo.id);
        //		if(BoardManager.Instance.isGameOver)
        //		{
        //			//if(curBoardTile.boardInfo.isGoal)
        //				BoardManager.Instance.ShowGameOver();
        //		}

        //		if(cobwebText!=null)
        //		{
        //			Destroy(cobwebText);
        //			cobwebText = null;
        //		}
        isChaseMoving = false;
        BoardManager.Instance.cobwebText.SetActive(false);

        UIManager.Instance.HideDiceNum();
        //Destroy(destShowEffect);

        //ShowDestMark(false,0,0);

        //bGlowDestinationTile = false;

        //BoardManager.Instance.movingSlider.SetActive(false);
        //if(!isAboutTeleport)
        BoardManager.Instance.isBoardPersonMoving = false;

        CheckCurPassingBoard(true);
        ReCalculateZ(false);
        //ReCalculateZ();
        //if(!isAboutTeleport)
        moveState = MoveState.Still;

        foreach (BoardTile tile in BoardManager.Instance.destinationTiles)
        {
            if (curPassingBoard == tile)
            {
                ShowDestMark(false);
                break;
            }
        }


        if (isForwardMoving)
        {
            foreach (BoardPerson person in curPassingBoard.personOn)
            {
                if (person != this && person == battleOpponent)
                {
                    SoundManager.Instance.PlaySound(0);
                    break;
                }
            }

        }
        else
            BattleManager.Instance.isLoserActionDone = true;

        if (isBackExpelled)
        {
            ShowDestMark(false);
            isBackExpelled = false;
            glog.debug(SID + "  is back expelled false");
            DeactivateShield();
            AnimPlayByDir(backExpelledGetupAnimName, frontExpelledGetupAnimName);
            //anim.AnimationCompleted = this.ExpellGetupAnimComplete;
        }
        else
            DetermineAnimation(0, 0, 0);

        //		if(bChasing && (addPathQueue.Count + afterTeleportPathQueue.Count <=1)  ) //chase show after all move path except one
        //		{
        //			BoardManager.Instance.ShowUIOnPerson("Chase!",this);
        //			bChasing = false;
        //			
        //		}
        //		

        if (addPathQueue.Count > 0)
        {
            AddPathInfo pathInfo = addPathQueue.Dequeue();
            glog.debug("pop add path queue " + addPathQueue.Count);
            StartMoveTo(pathInfo.moveCount, pathInfo.addPath, false, true);
            return;
        }



        if (BoardManager.Instance.waitRollBtnShow)
        {
            BoardManager.Instance.waitRollBtnShow = false;
			UIManager.Instance.ShowMoveRollButton(true, BoardManager.Instance.deadLineReserve);
        }
        //if(BoardManager.Instance.rollButton.activeInHierarchy)
        //	BoardManager.Instance.rollButton.GetComponent<UIImageButton>().isEnabled = true;

        isTeleportDoing = false;
        if (isAboutTeleport)
        {
            StartTeleport(true);
        }

        if (isWaitingSelectPath)
        {
            ShowSelectPath();
        }
        else
        {
            CheckAllMoveDone();
        }

    }

    void ShowSelectPath()
    {
        if (HasCardAbnormal(AbnormalType.MOVE_DIRECTION))
            CardManager.Instance.ShowFirstActiveCardSkillEffect(SID, AbnormalType.MOVE_DIRECTION);
        BoardManager.Instance.ActivateDiceOverHead(this, DiceShapeType.Normal);
        isWaitingSelectPath = false;
        int index = 0;
        float ratioMax = 0;
        float ratioMin = 1;
        PathSelectIndicator indicator = null;
        PathSelectIndicator ratioMaxIndicator = null;
        PathSelectIndicator ratioMinIndicator = null;
        foreach (int bid in selectPathBoardID)
        {
            BoardTile targetTile = GetPathManager().GetBoardTile(bid);
            BoardTile backTile = GetPathManager().GetBoardTile(targetTile.boardInfo.pathInfo[mypath].backBoards[0]);
            Vector3 newPos = targetTile.GetTileCenter();//targetTile.transform.position;
            //newPos.z = -2;

            //newPos.y += 0.055f;

            if (targetTile.boardInfo.index_x - backTile.boardInfo.index_x > 0)
            {
                indicator = UIManager.Instance.CreatePathSelectIndicator(0, newPos, bid, SID, true, 0, selectPathDeadLine);
            }
            if (targetTile.boardInfo.index_y - backTile.boardInfo.index_y < 0)
            {
                indicator = UIManager.Instance.CreatePathSelectIndicator(1, newPos, bid, SID, true, 0, selectPathDeadLine);
            }
            if (targetTile.boardInfo.index_x - backTile.boardInfo.index_x < 0)
            {
                indicator = UIManager.Instance.CreatePathSelectIndicator(2, newPos, bid, SID, true, 0, selectPathDeadLine);
            }
            if (targetTile.boardInfo.index_y - backTile.boardInfo.index_y > 0)
            {
                indicator = UIManager.Instance.CreatePathSelectIndicator(3, newPos, bid, SID, true, 0, selectPathDeadLine);
            }
            if (targetTile.boardInfo.pathInfo[mypath].ratioToGoal > ratioMax)
            {
                ratioMax = targetTile.boardInfo.pathInfo[mypath].ratioToGoal;
                ratioMaxIndicator = indicator;
            }
            if (targetTile.boardInfo.pathInfo[mypath].ratioToGoal < ratioMin)
            {
                ratioMin = targetTile.boardInfo.pathInfo[mypath].ratioToGoal;
                ratioMinIndicator = indicator;
            }
            //ShowPredictDestinationTile(bid, index);
            index++;
        }
        if (ratioMaxIndicator != null)
            ratioMaxIndicator.isRatioGoalMax = true;
        if (ratioMinIndicator != null)
            ratioMinIndicator.isRatioGoalMin = true;
        selectPathBoardID.Clear();
    }

    public void ShowPossiblePath()
    {
        int diceGroup = 0;
        BoardTile tileToCheck = curBoardTile;
        if (crossWayTile != null)
            tileToCheck = crossWayTile;
        crossWayTile = null;
        glog.debug("tileToCheck=" + tileToCheck.boardInfo.id);
        float ratioMax = 0;
        float ratioMin = 1;
        PathSelectIndicator indicator = null;
        PathSelectIndicator ratioMaxIndicator = null;
        PathSelectIndicator ratioMinIndicator = null;
        foreach (int bid in tileToCheck.boardInfo.pathInfo[mypath].forwardBoards)
        {
            glog.debug("forwards=" + bid);
            BoardTile targetTile = GetPathManager().GetBoardTile(bid);
            Vector3 newPos = targetTile.GetTileCenter();//targetTile.transform.position;
            //newPos.z = -2;
            //newPos.y += 0.055f;
            if (targetTile.boardInfo.index_x - tileToCheck.boardInfo.index_x > 0)
            {
                indicator = UIManager.Instance.CreatePathSelectIndicator(0, newPos, bid, SID, false, diceGroup, selectPathDeadLine);
            }
            if (targetTile.boardInfo.index_y - tileToCheck.boardInfo.index_y < 0)
            {
                indicator = UIManager.Instance.CreatePathSelectIndicator(1, newPos, bid, SID, false, diceGroup, selectPathDeadLine);
            }
            if (targetTile.boardInfo.index_x - tileToCheck.boardInfo.index_x < 0)
            {
                indicator = UIManager.Instance.CreatePathSelectIndicator(2, newPos, bid, SID, false, diceGroup, selectPathDeadLine);
            }
            if (targetTile.boardInfo.index_y - tileToCheck.boardInfo.index_y > 0)
            {
                indicator = UIManager.Instance.CreatePathSelectIndicator(3, newPos, bid, SID, false, diceGroup, selectPathDeadLine);
            }

            if (targetTile.boardInfo.pathInfo[mypath].ratioToGoal > ratioMax)
            {
                ratioMax = targetTile.boardInfo.pathInfo[mypath].ratioToGoal;
                ratioMaxIndicator = indicator;
            }
            if (targetTile.boardInfo.pathInfo[mypath].ratioToGoal < ratioMin)
            {
                ratioMin = targetTile.boardInfo.pathInfo[mypath].ratioToGoal;
                ratioMinIndicator = indicator;
            }

            //ShowPredictDestinationTile(bid, diceGroup);
            diceGroup++;
        }
        if (ratioMaxIndicator != null)
            ratioMaxIndicator.isRatioGoalMax = true;
        if (ratioMinIndicator != null)
            ratioMinIndicator.isRatioGoalMin = true;
    }

    void CheckAllMoveDone()
    {
        StopCoroutine("CoCheckAllMoveDone");
        StartCoroutine("CoCheckAllMoveDone");
    }

    IEnumerator CoCheckAllMoveDone()
    {
        glog.debug(SID + " CheckAllMoveDone waiting..");
        while (isTeleportDoing)
            yield return null;
        glog.debug(SID + " AllmoveDone");

        //ShowHidedSpawnNPC(false);

        if (BattleManager.Instance.waitCombatResultShow)
        {
            CheckAIThinkUI();
            BattleManager.Instance.ShowBattleResultAfterMoveDone(mytrans.position);
            while (!BattleManager.Instance.isBattleResultDone)
                yield return null;
            if (isBattleWinner)
            {
                while (bMovedToBattlePosition)
                    yield return null;
            }
        }


        AfterMoveEffect();
    }

    void AfterMoveEffect()
    {
        glog.debug("AfterMoveEffect");
        CheckCurPassingBoard(true);
        //ReCalculateZ();		
        // execute move done process
        //ActivateMoveBuf();
        //ShowNPC ();
        CheckItemGetEffect();
        CheckShowAchieveTempSkill();

        CheckAbnormalReserve();

        CheckChangeBoardStatus();

        //ShowCombatRollBtn();
		CheckUnitActivationChange();
        //if( !BoardManager.Instance.bCombatHappened)

        if (!isBackExpelled)
        {
            //	HudManager.Instance.ShowHPEffect(this, true,false);	
            HudManager.Instance.ShowHPChangeEffect_AfterMove();
            HudManager.Instance.ShowMPChangeEffect_AfterMove();
        }

        if (isRetired)
            SetRetireTransparent();

        /*
        if(BoardManager.Instance.bCaseRecoverMP)
        {
            BoardManager.Instance.bCaseRecoverMP = false;
            if(BoardManager.Instance.caseMPToRecover>0)
            {
                HudManager.Instance.IncreaseMainCharMP(SID, BoardManager.Instance.caseMPToRecover);
                ShowMPRecoverEffect();
            }
            BoardManager.Instance.caseMPToRecover = 0;
            glog.debug("CaseRecoverMP   "+BoardManager.Instance.otherPlayerCaseRecoverMP.Count);
            foreach (SidMpPair pair in BoardManager.Instance.otherPlayerCaseRecoverMP)
            {
                HudManager.Instance.IncreaseMainCharMP(pair.sid, pair.mp);
                StageManagerWrapper.GetBoardPerson(pair.sid).ShowMPRecoverEffect();
            }
            BoardManager.Instance.otherPlayerCaseRecoverMP.Clear();
        }*/


        if (bWaitForExtraTurn)
        {
            bWaitForExtraTurn = false;
            BoardManager.Instance.ShowUIRollMoveDice();
        }

        CheckAIThinkUI();

        if (bWaitCombatRoll_attacker)
        {
            bWaitCombatRoll_attacker = false;
            BoardManager.Instance.ActivateDiceOverHead(this, DiceShapeType.Attacker);
            if (BoardManager.Instance.mySID == StageManagerWrapper.showUI_attackerID)
                UIManager.Instance.ShowUIBattleRoll(true, battleDeadLine, DiceShapeType.Attacker);
        }
        if (bWaitCombatRoll_defender)
        {
            bWaitCombatRoll_defender = false;
            ShowDefenderDiceUI();
        }

        if (bWaitActivateDiceOverHead)
        {
            bWaitActivateDiceOverHead = false;
            BoardManager.Instance.ActivateDiceOverHead(this, DiceShapeType.Normal);
        }


        ShowDirectionRollUI();


        if (bWaitDirectionRoll)
        {
            bWaitDirectionRoll = false;
            RollDirectionDice();
        }

        //		if(!isForwardMoving)
        //		{
        //			isBackExpelled = false;
        //			glog.debug(SID+ "  is back expelled false");
        //		}

        if (bWaitForVictoryGame)
        {
            bWaitForVictoryGame = false;
            PlayVictoryAnim(2);
        }

        if (isLapChanged)
        {
            // force lap change ( happens by not passing start board.  ex: casting teleport skill to play who is on another lap )
            isLapChanged = false;
            //Debug.LogError("force set lapchange");
        }

        //		if(StageManagerWrapper.reserveCreatePawnPacket!=null)
        //		{
        //			StageManagerWrapper.CreateNewRunner(StageManagerWrapper.reserveCreatePawnPacket);
        //			StageManagerWrapper.reserveCreatePawnPacket=null;
        //		}


        ShowHidedSpawnNPC(false);


        SoundManager.Instance.PlaySound(21);

        //MainHUDUI.Instance.UpdateMoveMapmarker(true);
    }

    void ShowDirectionRollUI()
    {
        if (bWaitDirectionRollUI)
        {
            bWaitActivateDiceOverHead = false;
            bWaitDirectionRollUI = false;
            ShowPossiblePath();
            BoardManager.Instance.ActivateDiceOverHead(this, DiceShapeType.Normal);
            UIManager.Instance.ShowUIDirectionRoll(true, directionRollDeadLine);
        }
    }

    public void WaitShowDirectionRollUI()
    {
        bWaitDirectionRollUI = true;
        if (!IsMovingOrWaitMoving())
            ShowDirectionRollUI();
    }

    void CheckAIThinkUI()
    {
        if (bWaitActivateDiceOverHead_aibattle)
        {
            BoardManager.Instance.isAttackerAIThinkingShowed = true;
            bWaitActivateDiceOverHead_aibattle = false;
            BoardManager.Instance.ActivateDiceOverHead(this, DiceShapeType.Attacker);
            BoardManager.Instance.ShowDiceUIBattle(this, null, null, true);

        }

        if (BoardManager.Instance.bWaitDefenderAIThink)
        {
            BoardManager.Instance.bWaitDefenderAIThink = false;
            BoardManager.Instance.ActivateDiceOverHead(StageManagerWrapper.GetBoardPerson(StageManagerWrapper.manager.combatInfo_defenderSID), DiceShapeType.Defender);
            BoardManager.Instance.ShowDiceUIBattle(StageManagerWrapper.GetBoardPerson(StageManagerWrapper.manager.combatInfo_defenderSID), null, null, false);
        }
    }

    public void ShowDefenderDiceUI()
    {
        if (BoardManager.Instance.mySID == StageManagerWrapper.showUI_defenderID)
            UIManager.Instance.ShowUIBattleRoll(true, battleDeadLine, DiceShapeType.Defender);
    }

    public void RollDirectionDice()
    {
        ShowPossiblePath();
        StartCoroutine("CoRollDirectionDice");
    }

    IEnumerator CoRollDirectionDice()
    {
        while (!BoardManager.Instance.bShowDiceNumCompleted)
            yield return null;
        isDirectionDice = true;
        byte[] nDiceList = { (byte)BoardManager.Instance.diceValue_direction };
        BoardManager.Instance.ActivateDiceOverHead(this, DiceShapeType.Normal);
        PlayDiceHitAnim(nDiceList);
    }

    public void ShowHidedSpawnNPC(bool isDecoyBySkill)
    {
        if (BoardManager.Instance.hidedSpawnNPC == null)
            return;
        StartCoroutine(CoShowHidedSpawnNPC(isDecoyBySkill));
    }

    IEnumerator CoShowHidedSpawnNPC(bool isDecoyBySkill)
    {
        if (BoardManager.Instance.hidedSpawnNPC != null)
        {
            //isFallDone = false;
            glog.debug("CoShowHidedSpawnNPC");
            yield return new WaitForSeconds(0.2f);

            //			if(isDecoyBySkill)
            //			{
            //				while(!BoardManager.Instance.isShowDiceUIDone)
            //					yield return null;
            //			}

            BoardManager.Instance.hidedSpawnNPC.gameObject.renderer.enabled = true;
            BoardManager.Instance.hidedSpawnNPC.tagPerson.SetVisibleTagName(true);
            float upToY = 1.6f;
            Vector3 newPos = BoardManager.Instance.hidedSpawnNPC.transform.position;
            newPos.y += 1.6f;
            BoardManager.Instance.hidedSpawnNPC.transform.position = newPos;
            yield return null;
            //iTween.MoveBy(BoardManager.Instance.hidedSpawnNPC.gameObject, iTween.Hash("position", new Vector3(0,-upToY,0), "easetype","easeInBounce", "speed", 1.0f) );

            if (isDecoyBySkill)
            {
                sprite.color = new Color(1, 1, 1, 0.7f);
            }


            //BoardManager.Instance.RestartFSM( BoardManager.Instance.hidedSpawnNPC.gameObject, "fall");
            iTween.MoveTo(BoardManager.Instance.hidedSpawnNPC.gameObject, iTween.Hash("position", curBoardTile.GetPlayerPos(), "easetype", "easeInCubic", "time", 1.0f));
            yield return new WaitForSeconds(1.0f);
            iTween.PunchPosition(BoardManager.Instance.hidedSpawnNPC.gameObject, new Vector3(0, 0.2f, 0), 0.1f);
            //create particle ground hit;

            GameObject goEff = EffectManager.Instance.CreateEffect(10);
            goEff.transform.parent = BoardManager.Instance.hidedSpawnNPC.transform;
            goEff.transform.localPosition = EffectManager.Instance.GetPrefab(10).transform.localPosition;
            goEff.transform.localScale = EffectManager.Instance.GetPrefab(10).transform.localScale;
            goEff.transform.localRotation = EffectManager.Instance.GetPrefab(10).transform.localRotation;
            Destroy(goEff, 3.0f);
            BoardManager.Instance.hidedSpawnNPC.shadow.renderer.enabled = true;
            yield return new WaitForSeconds(0.3f);
            //CreateFootSmoke(16, BoardManager.Instance.hidedSpawnNPC.transform.position);
            //yield return new WaitForSeconds(0.1f);
            BoardManager.Instance.hidedSpawnNPC.isFalling = false;
            BoardManager.Instance.hidedSpawnNPC = null;
        }
    }


    public void ShowBoundObject()
    {

        SoundManager.Instance.PlaySound(20);
        StartCoroutine("BindObjectFadeOut");
    }

    IEnumerator BindObjectFadeOut()
    {

        BoardManager.Instance.bindObj_back.SetActive(true);
        BoardManager.Instance.bindObj_front.SetActive(true);

        Vector3 newPos = curBoardTile.GetTileCenter();//curBoardTile.transform.position;
        //newPos.x += 0.004732f;
        //newPos.y += 0.114471f;
        newPos.z = BoardManager.CalcZFromY_PlayerBack(transform.position.z);
        BoardManager.Instance.bindObj_back.transform.position = newPos;

        newPos = curBoardTile.GetTileCenter();//transform.position;
        //newPos.x += 0.004732f;
        //newPos.y += 0.117365f;
        newPos.z = BoardManager.CalcZFromY_PlayerFront(transform.position.z);
        BoardManager.Instance.bindObj_front.transform.position = newPos;

        tk2dSprite backSprite = BoardManager.Instance.bindObj_back.GetComponent<tk2dSprite>();
        tk2dSprite frontSprite = BoardManager.Instance.bindObj_front.GetComponent<tk2dSprite>();
        BoardManager.Instance.bindObj_back.GetComponent<tk2dSpriteAnimator>().Play();
        BoardManager.Instance.bindObj_front.GetComponent<tk2dSpriteAnimator>().Play();

        yield return new WaitForSeconds(1.0f);

        float alphaSprite = 1.0f;
        while (alphaSprite > 0)
        {
            alphaSprite -= 2 * Time.deltaTime;
            if (alphaSprite < 0)
                alphaSprite = 0;
            backSprite.color = new Color(1, 1, 1, alphaSprite);
            frontSprite.color = new Color(1, 1, 1, alphaSprite);
            yield return null;
        }
        //Destroy(bindObj_back);
        //Destroy(bindObj_front);
        backSprite.color = new Color(1, 1, 1, 1);
        frontSprite.color = new Color(1, 1, 1, 1);
        BoardManager.Instance.bindObj_back.SetActive(false);
        BoardManager.Instance.bindObj_front.SetActive(false);
    }

    public void StartTeleport(bool isTeleportFromMoving)
    {
        BoardManager.Instance.isBoardPersonMoving = true;
        moveState = MoveState.Moving;
        isTeleportDoing = true;
        SoundManager.Instance.PlaySound(22);
        isAboutTeleport = false;
        if (teleportTempObj == null)
        {
            glog.debug("teleportTempObj created");
            teleportTempObj = new GameObject();
        }
        teleportTempObj.transform.position = transform.position;
        //Destroy(teleportTempObj, 3.0f);

        if (BoardManager.Instance.nCurTurn == nCurTurn)
            Camera.main.gameObject.GetComponent<CameraControl>().SetCameraFocus(teleportTempObj.transform);

        TeleportEffect(0);
        StartCoroutine(TeleportToBoard(isTeleportFromMoving));
        if (togetherTeleportPerson != null)
        {
            togetherTeleportPerson.StartTeleport(false);
            togetherTeleportPerson = null;
        }
    }

    IEnumerator TeleportToBoard(bool isTeleportFromMoving)
    {
        glog.debug(SID + "  TeleportToBoard to " + teleportBoardID);
        BoardTile tileToMove = GetPathManager().GetBoardTile(teleportBoardID);
        if (!tileToMove.boardInfo.isStart && !tileToMove.boardInfo.isGoal)
            EffectManager.Instance.CreateTeleportSpotEfffect(tileToMove);

        yield return new WaitForSeconds(0.3f);

        if (BoardManager.Instance.nCurTurn == nCurTurn)
        {
            teleportTempObj.transform.position = tileToMove.GetPlayerPos();
            Camera.main.gameObject.GetComponent<CameraControl>().SetCameraFocus(teleportTempObj.transform);
        }


        yield return new WaitForSeconds(0.4f);

        curBoardTile = tileToMove;
        mTargetBoard.Add(curBoardTile);
        DeterminAnimFromCurTile(false);
        glog.debug(SID + "  tileToMove  " + tileToMove.boardInfo.id);
        mytrans.position = GetTilePlayerPos(tileToMove, true);
        CheckCurPassingBoard(true);
        //ReCalculateZ();
        if (BoardManager.Instance.nCurTurn == nCurTurn)
            Camera.main.gameObject.GetComponent<CameraControl>().SetCameraFocus(transform);
        TeleportEffect(1);
        MainHUDUI.Instance.MoveMapMarker(gameOrder, curBoardTile.boardInfo.pathInfo[mypath].ratioToGoal, 0, isBoss, m_lapcount);
        yield return new WaitForSeconds(0.2f);
        if (afterTeleportPathQueue.Count > 0)
        {
            int index = 0;
            foreach (AddPathInfo pathInfo in afterTeleportPathQueue)
            {
                if (index == 0)
                    BoardManager.Instance.StartMovePawn(this, pathInfo.moveCount, pathInfo.addPath, false);
                else
                    AddPath(pathInfo.moveCount, pathInfo.addPath);
                index++;
            }
            afterTeleportPathQueue.Clear();
        }
        else
        {
            glog.debug("teleport is done");
            isTeleportDoing = false;
            moveState = MoveState.Still;
            BoardManager.Instance.isBoardPersonMoving = false;
            yield return new WaitForSeconds(0.3f);
            BoardManager.Instance.bUsedTeleportSkill = false;
            if (!isTeleportFromMoving)
                AfterMoveEffect();
        }
    }

    public void SetToChangeBoardStatus(int boardID, int height, int boardDataType, ChangeBoardReason changeReason)
    {
        isToChangeBoardStatus = true;
        boardIdToChange = boardID;
        boardHeightToChange = height;
        boardDataTypeToChange = boardDataType;
        boardChangeReason = changeReason;
    }

    void CheckChangeBoardStatus()
    {
        if (isToChangeBoardStatus)
        {
            isToChangeBoardStatus = false;
            BoardManager.Instance.ChangeBoardStatus(boardIdToChange, boardHeightToChange, boardDataTypeToChange, this, boardChangeReason);
        }
    }

	void CheckUnitActivationChange()
	{
		if(unitActivationPacketByBoard!=null)
		{
			CardManager.Instance.SetUnitActivationInfo_NonBattle(unitActivationPacketByBoard);
			unitActivationPacketByBoard=null;
		}
	}

    void ShowPredictDestinationTile(int bid, int index)
    {
        int nextId = bid;
        for (int i = 0; i < remainMoveCount - 1; i++)
        {
            BoardTile tile = GetPathManager().GetBoardTile(nextId);
            if (tile.boardInfo.pathInfo[mypath].forwardBoards.Count == 0)
                break;
            nextId = tile.boardInfo.pathInfo[mypath].forwardBoards[0];
        }

        //ShowDestMark(true, nextId, index);
        //BoardManager.Instance.ShowGlowTileEffect(GetPathManager().GetBoardTile(nextId));
    }



    public void MyTurnAlarm(int myTurn)
    {
        m_myTurn = myTurn;
        //HudManager.Instance.PlayGear(SID);
        PlayAlarmParticle();

        //		if(!bShowMyTurnAlarm)
        //		{
        //			bShowMyTurnAlarm = true;
        //			StartCoroutine( GlowEffect(0.5f, 1.5f) );
        //		}
    }

    public void PlayAlarmParticle()
    {
        //GameObject fx = HudManager.Instance.GetPanelChild(SID, "FX");
        //if(fx==null)
        //    return;
        //fx.SetActive(true);
        //ParticleSystem ps = fx.transform.FindChild("FX_circle").GetComponent<ParticleSystem>();
        //if(ps.isPlaying)
        //    return;
        //if(order==1)
        //    ps.startSize = 0.9f;
        //else
        //    ps.startSize = 0.7f;
        ////ps.startColor = IngameSetting.Instance.playerTagCircleColor[order-1];
        //ps.renderer.material = IngameSetting.Instance.turnAlarmMat[gameOrder-1];
        ////ps.gameObject.GetComponent<SetRenderQueue>().SetRenderQueueManual();
        //ps.Play();

        ////yield return new WaitForSeconds(3.0f);
        ////ps.Stop ();      


//        if (isMe)
//        {
//            bool isBot = HudManager.Instance.GetPanelChild(SID, "Panel_char").transform.Find("Bot").gameObject.activeSelf;
//
//            if (!isBot)  //나일때만 남은 시간 카운팅 보여줌
//            {
//                HudManager.Instance.SetTurnTimeCount(SID, true);
//            }
//        }
    }

    IEnumerator GlowEffect(float bound, float speed)
    {
        tk2dSprite sprite = gameObject.GetComponent<tk2dSprite>();
        Color reserveColor = sprite.color;
        float alpha = 1.0f;
        float alpha_delta = -speed;
        float sumTime = 0.0f;
        while (bShowMyTurnAlarm)
        {
            sumTime += Time.deltaTime;
            alpha += alpha_delta * Time.deltaTime;
            if (alpha < bound)
            {
                alpha = bound;
                alpha_delta = -alpha_delta;
            }
            if (alpha > 1.0f)
            {
                alpha = 1.0f;
                alpha_delta = -alpha_delta;
            }
            sprite.color = new Color(reserveColor.r * alpha, reserveColor.g * alpha, reserveColor.b * alpha, reserveColor.a);
            yield return null;
        }
        sprite.color = reserveColor;
    }

    public void AddPath(int mcount, int[] path)
    {
        if (isAboutTeleport)
        {
            afterTeleportPathQueue.Enqueue(new AddPathInfo(mcount, path));
            glog.debug("afterTeleportPathQueue sid=" + SID + "  pathQueue count=" + afterTeleportPathQueue.Count);
        }
        else
        {
            addPathQueue.Enqueue(new AddPathInfo(mcount, path));
            glog.debug("AddPath sid=" + SID + "  pathQueue count=" + addPathQueue.Count);
        }
    }


    void ShowCombatRollBtn()
    {
        if (bCanCombatRoll)
        {
            bCanCombatRoll = false;
            gameObject.GetComponent<CPawnWrapper>().CanCombatRoll = true;
            UIManager.Instance.CanCombatRoll(gameObject.GetComponent<CPawnWrapper>());
        }
    }

    public void SetWaitingSelectPath(int boardId, DateTime deadLine)
    {
        selectPathDeadLine = deadLine;
        isWaitingSelectPath = true;
        selectPathBoardID.Add(boardId);
        if (moveState == MoveState.Still)
            ShowSelectPath();
    }

    bool IsAttackerBackward()
    {
        if (!isForwardMoving && IsAttacker())
            return true;
        return false;
    }

    bool IsAttacker()
    {
        //if(BoardManager.Instance.curTurnSID == SID)
        if (BattleManager.Instance.attackerID == SID)
            return true;
        return false;
    }

    public void DeletePawn()
    {
        if (BattleManager.Instance.bCombatHappened)
        {
            if (isBattleWinner)
            {
                if (!BattleManager.Instance.isWinnerActionDone)
                    isAboutToDelete = true;
                else
                    FadeOutDelete();
            }
            else
            {
                if (!BattleManager.Instance.isLoserActionDone)
                {
                    isAboutToDelete = true;
                    if (damageAnimationPlayed)
                    {
                        BattleManager.Instance.isLoserActionDone = true;
                        FadeOutDelete();
                        bMovedToBattlePosition = false;
                        if (battleOpponent.bMovedToBattlePosition)
                        {
                            battleOpponent.MoveToTileCenter();
                        }
                    }
                }
                else
                    FadeOutDelete();
            }
        }
        else
            FadeOutDelete();
        glog.debug("destroy pawn isAboutToDelete  " + SID);


    }



    public void FadeOutDelete()
    {
		if (battleOpponent != null)
		{
			if(battleOpponent.m_bonusLootInfo!=null)
				battleOpponent.m_isBonusLootEffectDoing=true;
		}
        StartCoroutine("CoFadeOutDelete");
    }

    IEnumerator CoFadeOutDelete()
    {
        if (curBoardTile.personOn.Contains(this))
            curBoardTile.personOn.Remove(this);
        isAboutToDelete = false;

        //		GameObject goEff = EffectManager.Instance.CreateEffect(25);
        //		goEff.transform.parent = transform;
        //		goEff.transform.localPosition = EffectManager.Instance.GetPrefab(25).transform.localPosition;
        //		Destroy(goEff,3.0f);	
        EffectManager.Instance.PlayEffectParent(25, transform);
        SoundManager.Instance.PlaySound(ESound.MonsterGhostAway);

        gameObject.GetComponent<SpriteManipulate>().ChangeAlphaDelay(0.0f, 1.5f, 0.5f, false);
        //Destroy(shadow);
        shadow.SetActive(false);
        BoardManager.Instance.boardPersonNPCList.Remove(this);
        StageManagerWrapper.objectMap.Remove(SID);

        if (battleOpponent != null)
        {
            battleOpponent.CheckItemGetEffectByNPC(this);

        }

		yield return new WaitForSeconds(2.0f);
		if (battleOpponent != null)
		{
			battleOpponent.CheckBonusLoot(this);
		}
        //Destroy(gameObject, 3.5f);
        yield return new WaitForSeconds(1.5f);
        gameObject.SetActive(false);
    }


    public void StartMoveTo(int moveCount, int[] targetBoardIds, bool isBackWard, bool isAddPathMove)
    {
        if (isAddPathMove)// assure moving state not to be proceeded by checking still state.
        {
            moveState = MoveState.Moving;
            BoardManager.Instance.isBoardPersonMoving = true;
        }
        StartCoroutine(CoStartMoveTo(moveCount, targetBoardIds, isBackWard, isAddPathMove));
    }

    IEnumerator CoStartMoveTo(int moveCount, int[] targetBoardIds, bool isBackWard, bool isAddPathMove)
    {
        crossWayTile = null;
        isForwardMoving = !isBackWard;
        if (isBackWard)
        {
            bMovedToBattlePosition = false;
            if (battleOpponent != null && battleOpponent.bMovedToBattlePosition)
            {
                battleOpponent.MoveToTileCenter();
            }
        }

        if (moveCount == 0)
        {
            glog.debug("StopMoving movecount zero");

            if (BoardManager.Instance.destinationTiles.Count > 0)
                StageManagerWrapper.camControl.CheckDestMarkWithinCamera();
            int index = 0;
            bShowMovingCourseDone.Clear();
            foreach (var pair in BoardManager.Instance.destinationTileBidDic)
            {
                BoardTile keytile = pair.Key;
                bShowMovingCourseDone.Add(false);
                StartCoroutine(CoShowMovingCourse(keytile, index));
                index++;
            }

            for (int i = 0; i < bShowMovingCourseDone.Count; i++)
            {
                while (!bShowMovingCourseDone[i])
                    yield return null;
            }

            BoardTile.AnimateMovingCourse();

            ShowDestMark(true);
            StopMoving(true);
            yield break;
        }
        if (isBackWard && moveCount >= 12)
        {
            HudManager.Instance.ShowAIEmotionChat(SID, "combat_lose_max");
            if (battleOpponent != null)
                HudManager.Instance.ShowAIEmotionChat(battleOpponent.SID, "combat_win_max");
        }
        glog.debug("StartMove  targetBoardIds.Length=" + targetBoardIds.Length + " movecount=" + moveCount);
        glog.debug("curboardId = " + curBoardTile.boardInfo.id);
        if (moveState == MoveState.Moving && !isAddPathMove)
        {
            Debug.LogError("current Moving...return");
            yield break;
        }

        if (targetBoardIds.Length == 0)
            yield break;

        bool isChaseMoveSpeedChange = false;
        isChaseMoving = false;
        if (isForwardMoving)
        {
            if (bChasing && chaseStartBoardID == targetBoardIds[0])
            {
                BoardManager.Instance.isBoardPersonMoving = true;
                //BoardManager.Instance.ShowUIOnPerson("Chase!",this);
                GameObject chaseEff = EffectManager.Instance.CreateEffect(23, transform.position);
                chaseEff.transform.parent = transform;
                chaseEff.transform.localPosition = EffectManager.Instance.GetPrefab(23).transform.position;
                SoundManager.Instance.PlaySound(17);
                if (HasCardAbnormal(AbnormalType.MODIFY_CHASE))
                    CardManager.Instance.ShowFirstActiveCardSkillEffect(SID, AbnormalType.MODIFY_CHASE);
                yield return new WaitForSeconds(1.5f);
                SoundManager.Instance.PlaySound(16);
                BoardManager.Instance.ShowUIOnPerson(UIType.UI_CHASE, this);
                bChasing = false;
                isChaseMoveSpeedChange = true;
                isChaseMoving = true;
            }
            //StopMoveBufEffect();
        }

        if (targetBoardIds.Length == 1 && curBoardTile.boardInfo.id == targetBoardIds[0])
        {
            Debug.LogError("curboardId same as targetBoardId : " + curBoardTile.boardInfo.id);
            yield break;
        }

        BoardManager.Instance.isBoardPersonMoving = true;

		while(m_isBonusLootEffectDoing)
			yield return null;

        moveSpeed = targetBoardIds.Length / 3.0f;
        if (moveSpeed < 1)
            moveSpeed = 1;
        if (moveSpeed > 4)
            moveSpeed = 4;
        if (isChaseMoveSpeedChange)
            moveSpeed = 1.5f * moveSpeed;

        if (moveSpeedManual > 0)
            moveSpeed = moveSpeedManual;

        originalMoveSpeed = moveSpeed;
        //StartCoroutine( ShowDiceLabel(targetBoardIds.Length) );
        int curId = curBoardTile.boardInfo.id;
        int nMoveXCount = 0;
        int nMoveYCount = 0;
        int nLastMoveX = 0;
        int nLastMoveY = 0;
        mTargetBoard.Clear();


        modifiedTargetBoardIds.Clear();
        List<int> candidateTargetBoardIds = new List<int>();
        if (isForwardMoving && targetBoardIds[0] != curId)
        {
            for (int nBackIndex = 0; nBackIndex < GetPathManager().GetBoardTile(targetBoardIds[0]).boardInfo.pathInfo[mypath].backBoards.Count; nBackIndex++)
            {
                int backBoardID = GetPathManager().GetBoardTile(targetBoardIds[0]).boardInfo.pathInfo[mypath].backBoards[nBackIndex];
                if (backBoardID != curId)
                {
                    for (int nBackIndex_2 = 0; nBackIndex_2 < GetPathManager().GetBoardTile(backBoardID).boardInfo.pathInfo[mypath].backBoards.Count; nBackIndex_2++)
                    {
                        int backBoardID_2 = GetPathManager().GetBoardTile(backBoardID).boardInfo.pathInfo[mypath].backBoards[nBackIndex_2];
                        if (backBoardID_2 != curId)
                            candidateTargetBoardIds.Add(backBoardID_2);
                        else
                        {
                            candidateTargetBoardIds.Clear();
                            break;
                        }
                    }

                    candidateTargetBoardIds.Add(backBoardID);
                }
                else
                {
                    candidateTargetBoardIds.Clear();
                    break;
                }
            }
        }

        foreach (int cid in candidateTargetBoardIds)
            modifiedTargetBoardIds.Add(cid);

        foreach (int tid in targetBoardIds)
        {
            modifiedTargetBoardIds.Add(tid);
        }

        BoardTile nextBoardTile = null;
        foreach (int nextId in modifiedTargetBoardIds)
        {
           // glog.debug("cur=" + curId + "    next target id=" + nextId);

            BoardTile curtile = GetPathManager().GetBoardTile(curId);
            if (curtile != nextBoardTile)
                mTargetBoard.Add(curtile);
            nextBoardTile = GetPathManager().GetBoardTile(nextId);
            mTargetBoard.Add(nextBoardTile);

            int nMoveX = (nextBoardTile.boardInfo.index_x - curtile.boardInfo.index_x);
            int nMoveY = (nextBoardTile.boardInfo.index_y - curtile.boardInfo.index_y);
            int heightDiff = nextBoardTile.height - curtile.height;
            nMoveXCount += nMoveX;
            nMoveYCount += nMoveY;
            if (nMoveX == 0 && nLastMoveX != nMoveX)
            {
                //glog.debug ("x add id="+curId);
                EnqueueToMoveList(curId);
                nMoveXCount = 0;
            }
            else if (nMoveY == 0 && nLastMoveY != nMoveY)
            {
                //glog.debug ("y add id="+curId);
                EnqueueToMoveList(curId);
                nMoveYCount = 0;
            }

            // add for special cases
            if (heightDiff != 0)
            {
                //glog.debug("heightDiff enque " + curId + "  " + nextId);
                EnqueueToMoveList(curId);
                EnqueueToMoveList(nextId);
            }
            else if (IsChangingToBumpyTile(curtile, nextBoardTile))
            {
               // glog.debug("change to bumpy enque " + curId + "  " + nextId);
                EnqueueToMoveList(curId);
                EnqueueToMoveList(nextId);
            }
            else if (IsChangingBumpyToNormalTile(curtile, nextBoardTile))
            {
                //glog.debug("change bumpy to normal  enque " + curId + "  " + nextId);
                EnqueueToMoveList(curId);
                EnqueueToMoveList(nextId);
            }
            else if (IsAvoidTile(curtile, nextBoardTile))
            {
                //glog.debug("is avoid tile " + curId + "  " + nextId);
                EnqueueToMoveList(curId);
                EnqueueToMoveList(nextId);
            }
            else if (isMoveFromStartFirstTime && curtile.boardInfo.isStart)
            {
                isMoveFromStartFirstTime = false;
                EnqueueToMoveList(nextId);
            }

            nLastMoveX = nMoveX;
            nLastMoveY = nMoveY;
            curId = nextId;
        }

        if (nMoveXCount != 0 || nMoveYCount != 0)
        {
            //glog.debug("remain move nMoveXCount="+nMoveXCount+"  nMoveYCount="+nMoveYCount);
            glog.debug("add id=" + curId);
            EnqueueToMoveList(curId);
        }

        glog.debug("moveToBoardList.count=" + moveToBoardList.Count);//+" test="+GetPathManager().GetBoardTile(curId).transform.position);
        //Vector3 newPos = new Vector3(GetPathManager().GetBoardTile(curId).transform.position.x, GetPathManager().GetBoardTile(curId).transform.position.y + 0.1f, -1);
        //destShowEffect = EffectManager.Instance.CreateEffect(0, newPos);

        if (isForwardMoving)
        {
            UIManager.Instance.ShowDiceNum();

            if (BoardManager.Instance.destinationTiles.Count > 0)
                StageManagerWrapper.camControl.CheckDestMarkWithinCamera();
            int index = 0;
            bShowMovingCourseDone.Clear();
            foreach (var pair in BoardManager.Instance.destinationTileBidDic)
            {
                BoardTile keytile = pair.Key;
                bShowMovingCourseDone.Add(false);
                StartCoroutine(CoShowMovingCourse(keytile, index));
                index++;
            }

            for (int i = 0; i < bShowMovingCourseDone.Count; i++)
            {
                while (!bShowMovingCourseDone[i])
                    yield return null;
            }

            BoardTile.AnimateMovingCourse();
            ShowDestMark(true);

            while (StageManagerWrapper.camControl.bProceedingDestMarkZoom)
                yield return null;
        }
        else
        {
            if (isBackExpelled)
            {
                moveSpeed = moveSpeed * 2;
                backExpellInitSpeed = moveSpeed;
                bBackExpellInitiated = true;
            }
        }

        MoveToDest();
    }

    IEnumerator CoShowMovingCourse(BoardTile keytile, int index)
    {
        int nShowStart = -1;
        for (int i = BoardManager.Instance.destinationTileBidDic[keytile].Count - 1; i >= 0; i--)
        {
            BoardTile btile = BoardManager.Instance.destinationTileBidDic[keytile][i];
            if (btile == curBoardTile)
                nShowStart = i;
            if (btile != curBoardTile && i < nShowStart)
            {
                bool bMaded = btile.MakeMovingCourse(index);
                if (bMaded)
                    yield return new WaitForSeconds(0.08f);
            }
        }
        bShowMovingCourseDone[index] = true;
    }

    public void ShowDestMark(bool show)
    {
        if (show)
        {
            if (BoardManager.Instance.destinationTiles.Count > 0)
                StageManagerWrapper.camControl.CheckDestMarkWithinCamera();
            int markCount = 0;
            foreach (BoardTile tile in BoardManager.Instance.destinationTiles)
            {
                BoardManager.Instance.ShowDestMark(gameOrder, tile, markCount);
                markCount++;
            }
        }
        else
        {
            BoardTile.DeleteAllMovingCourse();
            BoardManager.Instance.destinationTiles.Clear();
            BoardManager.Instance.HideDestMark();
        }
    }

    IEnumerator GlowDestinationTile(int bid)
    {
        float bound = 0.5f;
        float speed = 2.0f;
        bGlowDestinationTile = true;
        BoardTile tile = GetPathManager().GetBoardTile(bid);
        tk2dSprite tileSprite = tile.GetComponent<tk2dSprite>();
        Color reserveColor = tileSprite.color;
        float alpha = 1.0f;
        float alpha_delta = -speed;
        float sumTime = 0.0f;
        while (bGlowDestinationTile)
        {
            glog.debug("alpha=" + alpha);
            sumTime += Time.deltaTime;
            alpha += alpha_delta * Time.deltaTime;
            if (alpha < bound)
            {
                alpha = bound;
                alpha_delta = -alpha_delta;
            }
            if (alpha > 1.0f)
            {
                alpha = 1.0f;
                alpha_delta = -alpha_delta;
            }
            tileSprite.color = new Color(reserveColor.r * alpha, reserveColor.g * alpha, reserveColor.b * alpha, reserveColor.a);
            yield return null;
        }
        tileSprite.color = reserveColor;
    }



    void EnqueueToMoveList(int bid)
    {
        if (!moveToBoardList.Contains(bid) && bid != curBoardTile.boardInfo.id)
        {
            glog.debug("enqueue movelist  " + bid);
            moveToBoardList.Enqueue(bid);
        }
    }

    bool IsChangingToBumpyTile(BoardTile curTile, BoardTile nextTile)
    {
        if (nextTile.boardInfo.tilename == BoardInfo.TileName.road_bumpy_01 && curTile.boardInfo.tilename != BoardInfo.TileName.road_bumpy_01)
            return true;
        return false;
    }

    bool IsChangingBumpyToNormalTile(BoardTile curTile, BoardTile nextTile)
    {
        if (nextTile.boardInfo.tilename != BoardInfo.TileName.road_bumpy_01 && curTile.boardInfo.tilename == BoardInfo.TileName.road_bumpy_01)
            return true;
        return false;
    }

    bool IsAvoidTile(BoardTile curTile, BoardTile nextTile)
    {
        if (avoidTargetList.Count > 0)
        {
            if (curTile.personOn.Count >= 1)
            {
                foreach (BoardPerson person in curTile.personOn)
                {
                    if (avoidTargetList.Contains(person.SID))
                        return true;
                }
            }
            if (nextTile.personOn.Count >= 1)
            {
                foreach (BoardPerson person in nextTile.personOn)
                {
                    if (avoidTargetList.Contains(person.SID))
                        return true;
                }
            }
        }
        return false;
    }

    bool IsOnBumpyEffect(BoardTile curTile, BoardTile nextTile)
    {
        if (nextTile.boardInfo.tilename == BoardInfo.TileName.road_bumpy_01 && curTile.boardInfo.tilename == BoardInfo.TileName.road_bumpy_01)
            return true;
        if (IsChangingToBumpyTile(curTile, nextTile))
            return true;
        return false;
    }

    void MoveToDest()
    {
        moveState = MoveState.Moving;

        int nextId = moveToBoardList.Dequeue();
        glog.debug(" movetoDEst " + isBackExpelled);
        BoardTile nextTile = GetPathManager().GetBoardTile(nextId);
        int dx = nextTile.boardInfo.index_x - curBoardTile.boardInfo.index_x;
        int dy = nextTile.boardInfo.index_y - curBoardTile.boardInfo.index_y;



        string movEaseType = "linear";
        if (isBackExpelled)
        {
            FindMoveDir(-dx, -dy);
            movEaseType = "easeOutSine";
        }
        else
            FindMoveDir(dx, dy);
        //else
        //	movEaseType = "easeOutExpo";
        bool isLastMove = false;
        if (moveToBoardList.Count == 0)
        {
            isLastMove = true;
            glog.debug("is Last Move");
        }

        bool isNextTileAvoided = false;
        int avoidPersonID = IsAvoidTargetOn(nextTile);
        if (avoidPersonID != -1)
        {
            if (moveToBoardList.Count == 0)
            {
                if (addPathQueue.Count > 0)
                {
                    AddPathInfo pathInfo = addPathQueue.Dequeue();
                    for (int i = 0; i < pathInfo.moveCount; i++)
                    {
                        EnqueueToMoveList(pathInfo.addPath[i]);
                    }
                }
            }

            if (moveToBoardList.Count == 0)
            {
                crossWayTile = nextTile;
                StopMoving(false);
                return;
            }

            avoidTargetList.Remove(avoidPersonID);
            nSkipTileCountByAvoid = 1;
            nextId = moveToBoardList.Dequeue();
            nextTile = GetPathManager().GetBoardTile(nextId);
            glog.debug(" pop movelist queue again for avoid tile  " + nextId);

            int avoidPersonID_2 = IsAvoidTargetOn(nextTile);
            if (avoidPersonID_2 != -1)
            {
                if (moveToBoardList.Count == 0)
                {
                    if (addPathQueue.Count > 0)
                    {
                        AddPathInfo pathInfo = addPathQueue.Dequeue();
                        for (int i = 0; i < pathInfo.moveCount; i++)
                        {
                            EnqueueToMoveList(pathInfo.addPath[i]);
                        }
                    }
                }

                if (moveToBoardList.Count == 0)
                {
                    avoidTargetList.Add(avoidPersonID);
                    crossWayTile = nextTile;
                    StopMoving(false);
                    return;
                }

                avoidTargetList.Remove(avoidPersonID_2);
                nSkipTileCountByAvoid = 2;
                nextId = moveToBoardList.Dequeue();
                nextTile = GetPathManager().GetBoardTile(nextId);
                glog.debug(" pop2 movelist queue again for avoid tile  " + nextId);
            }

            isNextTileAvoided = true;
        }


        if (isNextTileAvoided)
        {
            BoardTile highTile = curBoardTile;
            if (nextTile.transform.position.y > curBoardTile.transform.position.y)
                highTile = nextTile;

            //Vector3 midPathVec = GetTilePlayerPos(curBoardTile,false);
            //midPathVec.y = GetTilePlayerPos(highTile,false).y + 0.3f;
            //midPathVec.x = curBoardTile.transform.position.x + (nextTile.transform.position.x - curBoardTile.transform.position.x)/2.0f;
            Vector3 avoidStartPos = GetTilePlayerPos(curBoardTile, false);
            Vector3 avoidEndPos = GetTilePlayerPos(nextTile, isLastMove);
            Vector3 midPathVec = (avoidStartPos + avoidEndPos) / 2;
            midPathVec.y += 0.3f;
            midPathVec.z = avoidStartPos.z;
            Vector3[] pathList1 = { avoidStartPos, midPathVec, avoidEndPos };
            glog.debug("avoid jump dest " + pathList1[2].x + "  " + pathList1[2].y + "  " + pathList1[2].z);
            float pauseDelay = 0.2f;
            StartCoroutine(CoDetermineAnimation(dx, dy, pauseDelay));
            iTween.MoveTo(gameObject, iTween.Hash("path", pathList1, "movetopath", false, "easetype", "linear", "oncomplete", "MoveContinue", "time", 0.5f, "delay", pauseDelay));
            //BoardManager.Instance.ShowUIOnPerson("Avoid!", this );
            SoundManager.Instance.PlaySound(15);
            BoardManager.Instance.ShowUIOnPerson(UIType.UI_AVOID, this);
            isJumping = true;
            shadow.SetActive(false);
        }
        else if (nextTile.height - curBoardTile.height != 0)
        {
            BoardTile highTile = curBoardTile;
            if (nextTile.height > curBoardTile.height)
                highTile = nextTile;

            Vector3 midPathVec = GetTilePlayerPos(curBoardTile, false);
            midPathVec.y = GetTilePlayerPos(highTile, false).y + 0.2f;
            midPathVec.x = curBoardTile.transform.position.x + (nextTile.transform.position.x - curBoardTile.transform.position.x) / 2.0f;
            Vector3[] pathList1 = { GetTilePlayerPos(curBoardTile, false), midPathVec, GetTilePlayerPos(nextTile, isLastMove) };
            glog.debug("jump dest " + pathList1[2].x + "  " + pathList1[2].y + "  " + pathList1[2].z);
            iTween.MoveTo(gameObject, iTween.Hash("path", pathList1, "movetopath", false, "easetype", "linear", "oncomplete", "MoveContinue", "onupdate", "MoveUpdate", "time", 0.3f));
            isJumping = true;
            shadow.SetActive(false);
        }
        else
        {
            if (!isBackExpelled && !isChaseMoving)
            {
                bool bMoveCostAdded = false;
                if (IsAbnormalState(AbnormalType.MODIFY_MOVE_COST))
                    bMoveCostAdded = true;
                bool isOnBumpyEffect = false;
                if (IsOnBumpyEffect(curBoardTile, nextTile))
                    isOnBumpyEffect = true;
                if ((isOnBumpyEffect || bMoveCostAdded) && isForwardMoving && !isBoss)
                {
                    if (isOnBumpyEffect)
                    {
                        nextTile.PlayBumpyEff();



                        Vector3 cobwebTextPos = transform.position;
                        cobwebTextPos.y += 0.3f;
                        BoardManager.Instance.cobwebText.SetActive(true);
                        BoardManager.Instance.cobwebText.transform.position = cobwebTextPos;
                        BoardManager.Instance.cobwebText.transform.parent = transform;
                    }
                    SoundManager.Instance.PlaySound(ESound.Tile_Bumpy);
                    moveSpeed = 0.6f;//originalMoveSpeed/2.0f;
                    isBumpyMoving = true;
                }
                else
                {
                    //					if(cobwebText!=null)
                    //					{
                    //						Destroy(cobwebText);
                    //						cobwebText = null;
                    //					}
                    BoardManager.Instance.cobwebText.SetActive(false);

                    //					if(cobweb!=null)
                    //					{
                    //						cobweb.GetComponent<ParticleSystem>().Stop();
                    //						Destroy(cobweb);
                    //						cobweb=null;
                    //					}
                    moveSpeed = originalMoveSpeed;
                    isBumpyMoving = false;
                }
            }
            if (bBackExpellInitiated)
            {
                bBackExpellInitiated = false;
                iTween.MoveTo(gameObject, iTween.Hash("position", GetTilePlayerPos(nextTile, false), "easetype", movEaseType, "oncomplete", "MoveContinue", "onupdate", "MoveUpdate", "speed", moveSpeed));
            }
            else
                iTween.MoveTo(gameObject, iTween.Hash("position", GetTilePlayerPos(nextTile, isLastMove), "easetype", movEaseType, "oncomplete", "MoveContinue", "onupdate", "MoveUpdate", "speed", moveSpeed));
        }

        float timeTo = (curBoardTile.transform.position - nextTile.transform.position).magnitude / moveSpeed;
        float ratiotogoal = nextTile.boardInfo.pathInfo[mypath].ratioToGoal;
        int laptogo = m_lapcount;
        if (isLapCountGoingToZero)
        {
            if (ratiotogoal == 0) // if next tile is start tile( in case circuit race) and is going to finish
                laptogo = 0;
        }
		else if(isLapChanged && isForwardMoving)
		{
			if (ratiotogoal == 0)// if next tile is start tile
				laptogo = m_lapcount-1;
		}
        bool bMapMarkerPositionOverlapped = MainHUDUI.Instance.MoveMapMarker(gameOrder, ratiotogoal, timeTo, isBoss, laptogo);
        if (bMapMarkerPositionOverlapped)
        {
            //	StopCoroutine( "CheckMapMarkerPosition" );
            //	StartCoroutine( "CheckMapMarkerPosition" );
        }
        //Camera.main.gameObject.GetComponent<CameraControl>().SetPlayerCamera(transform);	

        curBoardTile = nextTile;
        if (isBackExpelled)
            PlayExpelledAnim();
        else
        {
            if (isNextTileAvoided)
                DetermineAnimation(0, 0, 0);
            else
                DetermineAnimation(dx, dy, moveSpeed);
        }

    }

    IEnumerator CoDetermineAnimation(int dx, int dy, float delay)
    {
        yield return new WaitForSeconds(delay);
        DetermineAnimation(dx, dy, moveSpeed);
    }

    void FindMoveDir(int dx, int dy)
    {
        if (dx == 0 && dy < 0)
            SetMoveDir(MoveDir.TopLeft);
        else if (dx == 0 && dy > 0)
            SetMoveDir(MoveDir.BottomRight);
        else if (dy == 0 && dx > 0)
            SetMoveDir(MoveDir.TopRight);
        else if (dy == 0 && dx < 0)
            SetMoveDir(MoveDir.BottomLeft);
    }

    void ForceMoveDirFront()
    {
        if (moveDir == MoveDir.TopLeft)
            SetMoveDir(MoveDir.BottomRight);
        else if (moveDir == MoveDir.TopRight)
            SetMoveDir(MoveDir.BottomLeft);
    }

    public void SetMoveDir(MoveDir _dir)
    {
        moveDir = _dir;
        bool newFlipX;
        if (moveDir == MoveDir.TopLeft || moveDir == MoveDir.BottomRight)
            newFlipX = true;
        else
            newFlipX = false;
        bool bFlipXChanged = false;
        if (newFlipX != sprite.FlipX)
            bFlipXChanged = true;
        sprite.FlipX = newFlipX;
        if (bFlipXChanged)
            CheckShieldDir();
    }

    void DetermineAnimation(int dx, int dy, float _moveSpeed)
    {
        if (!anim)
            return;

        string backAnim;
        string frontAnim;
        bool isRun = false;
        if (dx == 0 && dy == 0)
        {
            backAnim = idleBackAnimName;
            frontAnim = idleFrontAnimName;
        }
        else
        {
            backAnim = backRunAnimName;
            frontAnim = frontRunAnimName;
            isRun = true;
        }

        if (moveDir == MoveDir.TopLeft || moveDir == MoveDir.TopRight)
            PlayAnim(backAnim);
        else
            PlayAnim(frontAnim);

        if (dx == 0 && dy == 0)
            SetAnimSpeed(backAnim, 1);
        else
            SetAnimSpeed(backAnim, _moveSpeed);


    }

    void PlayAnim(string animname)
    {
        tk2dSpriteAnimationClip clip = anim.GetClipByName(animname);
        if (animname == victoryAnimName)
        {
            clip.wrapMode = tk2dSpriteAnimationClip.WrapMode.Once;
            spriteFlipXReserved = sprite.FlipX;
            sprite.FlipX = false;
        }
        else if (animname == frontAttackAnimName || animname == backAttackAnimName)
        {
            clip.wrapMode = tk2dSpriteAnimationClip.WrapMode.Once;
            if (swordTrailPrefabDic_back.ContainsKey(charID) && !StageManagerWrapper.IsNPCType((int)pawnType))
            {
                bool isBackAnim = false;
                if (animname == backAttackAnimName)
                    isBackAnim = true;

                GameObject tmpPrefab = null;
                if (isBackAnim)
                {
                    if (swordTrailPrefabDic_back[charID] == null)
                    {
                        Debug.LogError("swordTrailPrefabDic back Load firstTime charID=" + charID);
                        swordTrailPrefabDic_back[charID] = Resources.Load("Prefabs/FX/SwordTrail/" + String.Format("SwordTrail_{0:00}_attack_a_back", charID)) as GameObject;
                    }
                    tmpPrefab = swordTrailPrefabDic_back[charID];
                    if (tmpPrefab != null)
                    {
                        if (swordTrailBack == null)
                            swordTrailBack = Instantiate(tmpPrefab) as GameObject;
                        swordTrailBack.SetActive(true);
                        swordTrailBack.transform.parent = transform;
                        swordTrailBack.transform.localPosition = tmpPrefab.transform.position;
                        swordTrailBack.transform.localRotation = tmpPrefab.transform.rotation;
                        swordTrailBack.transform.localScale = tmpPrefab.transform.localScale;
                        if (sprite.FlipX)
                            swordTrailBack.transform.localScale = new Vector3(-swordTrailBack.transform.localScale.x, swordTrailBack.transform.localScale.y, swordTrailBack.transform.localScale.z);
                        StartCoroutine("CoDisableSwordTrail", swordTrailBack);
                    }
                }
                else
                {
                    if (swordTrailPrefabDic_front[charID] == null)
                    {
                        Debug.LogError("swordTrailPrefabDic front Load firstTime charID=" + charID);
                        swordTrailPrefabDic_front[charID] = Resources.Load("Prefabs/FX/SwordTrail/" + String.Format("SwordTrail_{0:00}_attack_a_front", charID)) as GameObject;
                    }
                    tmpPrefab = swordTrailPrefabDic_front[charID];
                    if (tmpPrefab != null)
                    {
                        if (swordTrailFront == null)
                            swordTrailFront = Instantiate(tmpPrefab) as GameObject;
                        swordTrailFront.SetActive(true);
                        swordTrailFront.transform.parent = transform;
                        swordTrailFront.transform.localPosition = tmpPrefab.transform.position;
                        swordTrailFront.transform.localRotation = tmpPrefab.transform.rotation;
                        swordTrailFront.transform.localScale = tmpPrefab.transform.localScale;
                        if (sprite.FlipX)
                            swordTrailFront.transform.localScale = new Vector3(-swordTrailFront.transform.localScale.x, swordTrailFront.transform.localScale.y, swordTrailFront.transform.localScale.z);
                        StartCoroutine("CoDisableSwordTrail", swordTrailFront);
                    }
                }


            }
        }
        else if (animname == frontDamageAnimName || animname == backDamageAnimName)
            clip.wrapMode = tk2dSpriteAnimationClip.WrapMode.Once;
        else if (animname == dicehitAnimName)
        {
            clip.wrapMode = tk2dSpriteAnimationClip.WrapMode.Once;
            spriteFlipXReserved = sprite.FlipX;
            sprite.FlipX = false;
        }
        else if (animname == backDamageAnimName || animname == frontDamageAnimName)
        {
            clip.wrapMode = tk2dSpriteAnimationClip.WrapMode.Once;
            damageAnimationPlayed = false;
        }
        anim.Play(animname);

    }

    IEnumerator CoDisableSwordTrail(GameObject swordTrail)
    {
        yield return new WaitForSeconds(2.0f);
        swordTrail.SetActive(false);
        swordTrail.transform.parent = EffectManager.Instance.transform;
    }

    void SetAnimSpeed(string animname, float move_speed)
    {
        tk2dSpriteAnimationClip clip = anim.GetClipByName(animname);
        //glog.debug("anim.ClipFps="+anim.ClipFps+"  anim.CurrentClip.fps="+clip.fps+"  movespeed="+move_speed);
        if (move_speed > 2)
            move_speed = 2;
        if (move_speed < 0.5f)
            move_speed = 0.5f;
        anim.ClipFps = clip.fps * move_speed;
        if (isBumpyMoving && (animname == backRunAnimName || animname == frontRunAnimName))
            anim.ClipFps = clip.fps * 0.3f;
    }

    void SetToDefaultAnimFps(string animName)
    {
        tk2dSpriteAnimationClip clip = anim.GetClipByName(animName);
        anim.ClipFps = clip.fps;
    }

    public void PlayAttackAnim()
    {
        AnimPlayByDir(backAttackAnimName, frontAttackAnimName);
        bAttackEventTriggered = false;
        //		anim.AnimationEventTriggered = this.AnimAttackEvent;
        //anim.AnimationCompleted = this.AttackAnimCompleted;

    }

    void AnimPlayByDir(string backName, string frontName)
    {
        if (moveDir == MoveDir.TopLeft || moveDir == MoveDir.TopRight)
        {
            PlayAnim(backName);
            SetToDefaultAnimFps(backName);
        }
        else
        {
            PlayAnim(frontName);
            SetToDefaultAnimFps(frontName);
        }
    }

    public bool IsPC_or_AI()
    {
        if (StageManagerWrapper.IsPCType((int)pawnType) || pawnType == GAME_PAWN_TYPE.AI)
            return true;
        return false;
    }

    public bool IsBackExpelledAllowed()
    {
        if (isRetired)
            return false;
        if (isBoss)
            return false;
        if (IsAttacker() && !StageManagerWrapper.IsNPCType((int)pawnType))
            return true;
        else
        {
            if (IsPC_or_AI())
            {
                if (BoardManager.Instance.curMapRaceType == RaceType.COMBAT_RUN)
                    return true;
            }
        }
        if (battleOpponent.isBoss)
            return true;
        return false;
    }

    public void PlayDamagedAnim()
    {
        //GameObject damageEff = EffectManager.Instance.CreateEffectZ(14, transform.position);
        //Destroy(damageEff, 3.0f);

        EffectManager.Instance.PlayEffectParent(4, transform);
        EffectManager.Instance.DisableParticle(4, 2.0f);
        HudManager.Instance.ShowAIEmotionChat(SID, "combat_lose");
        HudManager.Instance.ChangeFace(SID, false);
        string backName = backDamageAnimName;
        string frontName = frontDamageAnimName;
        MakeShield();
        if (IsBackExpelledAllowed())
        {
            glog.debug(SID + " isBackExpelled");
            isBackExpelled = true;
            backName = backExpelledAnimName;
            frontName = frontExpelledAnimName;
            SoundManager.Instance.PlaySound(13);
            StartCoroutine("BackExpellSmoke");
        }
        else
        {
            BoardManager.Instance.RestartFSM(gameObject, "damaged_pop");
            //anim.AnimationCompleted = this.DamagedAnimCompleted;
        }
        AnimPlayByDir(backName, frontName);

    }

    IEnumerator BackExpellSmoke()
    {
        float timeSum = 100f;
        float timeSumSmoke = 100f;
        createFootSmokeCount = 0;
        while (isBackExpelled)
        {
            timeSum += Time.deltaTime;
            if (timeSum >= 0.395f)
            {
                timeSum = 0.0f;
                SoundManager.Instance.PlaySound(9);
            }

            timeSumSmoke += Time.deltaTime;
            if (timeSumSmoke >= 0.1f)
            {
                timeSumSmoke = 0.0f;
                createFootSmokeCount++;
                PlayFootSmoke(transform.position);
            }
            yield return null;
        }
    }

    void PlayFootSmoke(Vector3 pos)
    {
        pos.y -= upOffset;
        EffectManager.Instance.PlayFootSmoke(pos);
    }

    void PlayExpelledAnim()
    {
        AnimPlayByDir(backExpelledAnimName, frontExpelledAnimName);
    }

    void AnimCompleteCallBack(tk2dSpriteAnimator animator, tk2dSpriteAnimationClip clip)
    {
        if (clip.name == backAttackAnimName || clip.name == frontAttackAnimName ||
            clip.name == backExpelledGetupAnimName || clip.name == frontExpelledGetupAnimName || clip.name == dicehitAnimName)
        {
            if (clip.name == dicehitAnimName)
                sprite.FlipX = spriteFlipXReserved;
            glog.debug(clip.name + "  anim completed");
            DetermineAnimation(0, 0, 0);
        }
        else if (clip.name == backSkillCastAnimName || clip.name == frontSkillCastAnimName)
        {
            glog.debug("skill anim completed");
            bCastedSkill = false;
            DetermineAnimation(0, 0, 0);
        }
        else if (clip.name == backDamageAnimName || clip.name == frontDamageAnimName)
        {
            DeactivateShield();
            glog.debug("damaged anim completed");
            damageAnimationPlayed = true;
            DetermineAnimation(0, 0, 0);
            isDamagedAnimCompleted = true;
            if (isAboutToDelete)
            {
                if (BattleManager.Instance.loserID == SID)
                    BattleManager.Instance.isLoserActionDone = true;
                FadeOutDelete();
                bMovedToBattlePosition = false;
                if (battleOpponent.bMovedToBattlePosition)
                {
                    battleOpponent.MoveToTileCenter();
                }
            }
            else if (isRetired)
            {
                if (BattleManager.Instance.loserID == SID)
                    BattleManager.Instance.isLoserActionDone = true;
                SetRetireTransparent();
                bMovedToBattlePosition = false;
                if (battleOpponent.bMovedToBattlePosition)
                {
                    battleOpponent.MoveToTileCenter();
                }
            }
        }
        else if (clip.name == victoryAnimName)
        {
            glog.debug("victory anim completed");
            sprite.FlipX = spriteFlipXReserved;
            if (victoryAnimRepeat > 0)
            {
                victoryAnimRepeat--;
                PlayVictoryAnim(victoryAnimRepeat);
            }
            else
            {
                CheckItemGetEffect();
                CheckShowAchieveTempSkill();
                CheckAbnormalReserve();
				CheckUnitActivationChange();
                DetermineAnimation(0, 0, 0);
                BattleManager.Instance.SetWinnerActionDone();
                HudManager.Instance.ShowMPChangeEffect_AfterMove();
                ShowHidedSpawnNPC(false);

                if (isAboutToDelete)
                    FadeOutDelete();
                if (isRetired)
                {
                    HudManager.Instance.ShowHPChangeEffect();
                    SetRetireTransparent();
                }
            }
        }

    }

    void AnimEventCallBack(tk2dSpriteAnimator animator, tk2dSpriteAnimationClip clip, int frameNum)
    {
        if (clip.name == backRunAnimName || clip.name == frontRunAnimName)
        {
            string eventInfo = clip.GetFrame(frameNum).eventInfo;
            if (eventInfo == "left")
            {
                SoundManager.Instance.PlaySound(12);
            }
            else if (eventInfo == "right")
            {
                SoundManager.Instance.PlaySound(11);
            }
            else if (eventInfo == "flap")
            {
                SoundManager.Instance.PlaySound(50);
            }
        }
        else if (clip.name == backSkillCastAnimName || clip.name == frontSkillCastAnimName)
        {
            string eventInfo = clip.GetFrame(frameNum).eventInfo;
            if (eventInfo == "hit")
            {
                EffectManager.Instance.PlayEffectParent(12, transform);
            }
        }
        else if (clip.name == backAttackAnimName || clip.name == frontAttackAnimName)
        {
            string eventInfo = clip.GetFrame(frameNum).eventInfo;
            if (eventInfo == "attack")
            {
                glog.debug(SID + "  Anim Event attack");
                battleOpponent.PlayDamagedAnim();
                bAttackEventTriggered = true;
                HudManager.Instance.ShowAIEmotionChat(SID, "combat_win");
                SoundManager.Instance.PlaySound(8);
            }
        }
        else if (clip.name == dicehitAnimName)
        {
            string eventInfo = clip.GetFrame(frameNum).eventInfo;
            if (eventInfo == "hit")
            {
                glog.debug(SID + "  Anim Event dice hit");
                bDiceHitTriggered = true;
                BoardManager.Instance.PlayDiceOverHeadAnim(nDice, this, isDirectionDice);
                isDirectionDice = false;
            }
        }
    }

    public void PlayDiceHitAnim(byte[] dice)
    {
        nDice = new int[dice.Length];
        for (int i = 0; i < dice.Length; i++)
            nDice[i] = dice[i];

        if (BoardManager.Instance.boardPersonNPCList.Contains(this))
        {
            bDiceHitTriggered = true;
            //BoardManager.Instance.RestartFSM(gameObject, "dicehit");
            BoardManager.Instance.PlayDiceOverHeadAnim(nDice, this, isDirectionDice);
            isDirectionDice = false;
            return;
        }

        PlayAnim(dicehitAnimName);
        SetToDefaultAnimFps(dicehitAnimName);
        //anim.AnimationEventTriggered = this.AnimDiceHitEvent;
        //anim.AnimationCompleted = this.ExpellGetupAnimComplete;
        bDiceHitTriggered = false;

    }

    void MoveContinue()
    {
        glog.debug(SID + " MoveContinue");
        if (isJumping)
        {
            shadow.SetActive(true);
            isJumping = false;
        }
        if (moveToBoardList.Count > 0)
            MoveToDest();
        else
        {
            StopMoving(false);
        }
    }

    public void TeleportEffect(float scale_x)
    {
        Vector3 effPos = new Vector3(transform.position.x, transform.position.y - upOffset, -2);
        //GameObject effGo = EffectManager.Instance.CreateEffect(0, effPos);
        //Destroy(effGo, 2.0f);
        EffectManager.Instance.PlayTeleportEff((int)scale_x, effPos);
        StartCoroutine(Teleport_ScaleChange(scale_x));
    }

    IEnumerator Teleport_ScaleChange(float scale_x)
    {
        yield return new WaitForSeconds(0.2f);
        iTween.ScaleTo(gameObject, iTween.Hash("scale", new Vector3(scale_x, 1, 1), "time", 0.2f));
    }

    //	public void ReserveTeleport_afterCombat(int boardID)
    //	{
    //		teleportBoardID_afterCombat = boardID;
    //	}

    public void ReserveTeleport(int boardID, bool teleportRightNow)
    {
        glog.debug("teleportRightNow " + teleportRightNow);
        isAboutTeleport = true;
        teleportBoardID = boardID;
        if (teleportRightNow)
            StartTeleport(false);
    }

    public bool IsMovingOrWaitMoving()
    {
        if (moveState == MoveState.Moving || moveState == MoveState.WaitMoving)
            return true;
        return false;
    }

    public void ShowItemGetEffect(bool isUnit, string itemName, int itemAmount, bool bGetFromNPC, bool bGetByPassingBoard, int boardId, bool bonusLoot)
    {
        //Debug.LogError(SID+" ShowItemGetEffect "+bGetByPassingBoard+"  "+boardId);
        if (bGetByPassingBoard)
        {
            bool needCreate = true;
            foreach (ItemGetEffectInfo eInfo in itemGetEffectByPassBoard)
            {
                if (!eInfo.isActive)
                {
                    eInfo.isUnit = isUnit;
                    eInfo.itemName = itemName;
                    eInfo.itemAmount = itemAmount;
                    eInfo.boardId = boardId;
                    eInfo.isActive = true;
                    needCreate = false;
                    break;
                }
            }
            if (needCreate)
            {
                ItemGetEffectInfo effInfo = new ItemGetEffectInfo();
                effInfo.isUnit = isUnit;
                effInfo.itemName = itemName;
                effInfo.itemAmount = itemAmount;
                effInfo.boardId = boardId;
                effInfo.isActive = true;
                itemGetEffectByPassBoard.Add(effInfo);
                //Debug.LogError("need create  "+itemGetEffectByPassBoard.Count);
            }
        }
        else
        {
			if(bonusLoot) {
				m_bonusLootInfo = new ItemGetEffectInfo();
				m_bonusLootInfo.isUnit = isUnit;
				m_bonusLootInfo.itemName = itemName;
				m_bonusLootInfo.itemAmount = itemAmount;
				m_bonusLootInfo.boardId = boardId;
				m_bonusLootInfo.isActive = true;
			}
			else
			{
	            itemNameToGet = itemName;
	            itemNameToGet_isUnit = isUnit;
	            itemAmountToGet = itemAmount;
	            if (IsMovingOrWaitMoving() || bMovedToBattlePosition)
	            {
	                if (bGetFromNPC)
	                    bShowItemGetEffect_fromNPC = true;
	                else
	                    bShowItemGetEffect = true;

	            }
	            else
	            {
	                // temporaly disable
	                //MainHUDUI.Instance.ShowItemGetEffect(isUnit, this, itemNameToGet);
	            }
			}
        }
    }

    public void ReCalculateZ(bool bIsMeCheck)
    {
        if (curPassingBoard != null)
        {
            Vector3 newPos = mytrans.position;
            bool isMoving = false;
            if (moveState == MoveState.Moving)
                isMoving = true;
            if (bIsMeCheck)
                newPos.z = BoardManager.CalcPlayerZFromTile(curPassingBoard.transform.position.z, order, isMe, isMoving);//(transform.position.y-upOffset, SID);
            else
                newPos.z = BoardManager.CalcPlayerZFromTile(curPassingBoard.transform.position.z, order, false, isMoving);

            mytrans.position = newPos;
            z_to_apply = newPos.z;
        }
    }

    public bool ReCalculateZ_SameTileBattle()
    {
        // 두명이 같은 보드에  있을경우 z order 계산. 전투중에만
        if (curBoardTile.personOn.Count > 1)
        {
            foreach (BoardPerson person in curBoardTile.personOn)
            {
                if (person.SID != SID && person == battleOpponent)
                {
                    Vector3 newPos = mytrans.position;
                    bool isFront = true;
                    if (transform.position.y > person.transform.position.y)
                        isFront = false;
                    newPos.z = BoardManager.CalcPlayerZFromSameTile(curBoardTile.transform.position.z, isFront);
                    mytrans.position = newPos;
                    Vector3 opponentPos = battleOpponent.transform.position;
                    opponentPos.z = BoardManager.CalcPlayerZFromSameTile(curBoardTile.transform.position.z, !isFront);
                    battleOpponent.transform.position = opponentPos;
                    return true;
                }
            }
        }
        return false;
    }



    void MoveUpdate()
    {
        CheckCurPassingBoard(false);
        //ReCalculateZ();

        if (isBackExpelled)
        {
            moveSpeed -= backExpellInitSpeed * Time.deltaTime;
            if (moveSpeed < 0.5)
                moveSpeed = 0.5f;
            //glog.debug("mocespeed="+moveSpeed);
        }
    }

    public int IsAvoidTargetOn(BoardTile tile)
    {
        if (avoidTargetList.Count > 0)
        {
            foreach (BoardPerson person in tile.personOn)
            {
                if (avoidTargetList.Contains(person.SID))
                {
                    //avoidTargetList.Remove(person.SID);
                    return person.SID;
                }
            }
        }
        return -1;
    }

    public void CheckCurPassingBoard(bool isCurTileCheck)
    {
        BoardTile newbt = curBoardTile;
        Vector3 myCheckPos = transform.position;
        myCheckPos.y -= upOffset;

        if (!isCurTileCheck)
        {
            float distx = 0;
            float disty = 0;
            float minDist = 99;
            foreach (BoardTile tile in mTargetBoard)
            {
                distx = Mathf.Abs(myCheckPos.x - tile.GetTileCenter().x);
                disty = Mathf.Abs(myCheckPos.y - tile.GetTileCenter().y);
                if (distx + disty < minDist)
                {
                    minDist = distx + disty;
                    newbt = tile;
                }
            }
        }

        if (newbt != curPassingBoard)
        {
            curPassingBoard.personOn.Remove(this);
            curPassingBoard = newbt;
            curPassingBoard.DeleteMovingCourse();
            curPassingBoard.personOn.Add(this);
            ReCalculateZ(false);
            CheckItemGetEffectByPassingBoard(curPassingBoard.boardInfo.id);
            HudManager.Instance.ShowHPChangeEffect_Passing(curPassingBoard.boardInfo.id);
            HudManager.Instance.ShowMPChangeEffect_PassingMove(curPassingBoard.boardInfo.id);
            if (isForwardMoving && moveState == MoveState.Moving)
            {
                int nDecreaseAdd = 0;
                if (IsAbnormalState(AbnormalType.MODIFY_MOVE_COST))
                    nDecreaseAdd = GetAbnormalParam(AbnormalType.MODIFY_MOVE_COST);
                if (newbt.boardInfo.tilename == BoardInfo.TileName.road_bumpy_01)
                    UIManager.Instance.DecreaseDiceNum(this,-2 - nSkipTileCountByAvoid - nDecreaseAdd);
                else
                    UIManager.Instance.DecreaseDiceNum(this,-1 - nSkipTileCountByAvoid - nDecreaseAdd);
                nSkipTileCountByAvoid = 0;
            }
        }

        // set shadow pos
        Vector3 hitPos = myCheckPos;
        hitPos.z = newbt.transform.position.z - 0.001f;
        shadow.transform.position = hitPos;

    }
    /*
    public void CheckCurPassingBoard_physics()
    {
        RaycastHit hit;
        Vector3 myCheckPos = transform.position;
        myCheckPos.y -= upOffset;
        myCheckPos.z = -1;
        //glog.debug(LayerMask.NameToLayer("BoardTile")+" mycheckpos = "+myCheckPos.x+ "  "+myCheckPos.y);
        if (Physics.Raycast( myCheckPos, Vector3.forward, out hit, 1000, 1 << LayerMask.NameToLayer("BoardTile") )  )
        {
            if(hit.collider.gameObject.tag == "Board Tile")
            {
                BoardTile newbt = hit.collider.gameObject.GetComponent<BoardTile>();
                if(newbt != curPassingBoard)
                {
                    curPassingBoard.personOn.Remove(this);
                    curPassingBoard = newbt;
                    curPassingBoard.personOn.Add (this);
					
                }
                Vector3 hitPos = hit.point;
                hitPos.z = newbt.transform.position.z - 0.001f;
                shadow.transform.position = hitPos;
//				if(groundTag!=null)
//				{
//					hitPos.z -= 0.0001f;
//					groundTag.transform.position = hitPos;
//				}
            }
        }		
		
        MainHUDUI.Instance.UpdateMoveMapmarker(false);
    }
    */
    public void SetRetire(bool bRetire)
    {
        isRetired = bRetire;
        if (isRetired)
        {
        }
        else
        {
            UIManager.Instance.HideRebirthWindow();
            StageManagerWrapper.camControl.SetCameraFocus(transform);
            gameObject.SetActive(true);
            StartCoroutine("ChangeToRebirth");
        }
    }

    IEnumerator ChangeToRebirth()
    {
        if (isMe)
        {
            BoardManager.Instance.bDuringRebirth = true;
            //			Camera.main.gameObject.GetComponent<GrayscaleEffect>().enabled = false;
            //			HudManager.Instance.grayEffect.enabled = false;
        }

        Destroy(tomb);
        //tomb.SetActive(false);
        GameObject goEff = EffectManager.Instance.CreateEffect(19);//FX_Rebirth3
        goEff.transform.parent = transform;
        goEff.transform.localPosition = EffectManager.Instance.GetPrefab(19).transform.localPosition;
        Destroy(goEff, 5.0f);

		HudManager.Instance.SetRetiredPanelGray(SID,false);

        float alpha = 0;
        while (alpha < 1)
        {
            alpha += Time.deltaTime;
            if (alpha > 1)
                alpha = 1;
            sprite.color = new Color(1, 1, 1, alpha);
            yield return null;
        }

        yield return new WaitForSeconds(2.5f);
        if (isMe)
            BoardManager.Instance.bDuringRebirth = false;

    }

    public void SetRetireTransparent()
    {
        //sprite.color = new Color(1,1,1,0.5f);

        StartCoroutine("ChangeToTomb");



    }

    IEnumerator ChangeToTomb()
    {
        AchievementCell.DoShowAchieve(this, "dead");
        HudManager.Instance.ShowAIEmotionChat(SID, "dead");
        HudManager.Instance.ChangeFace(SID, false);
        GameObject goEff = EffectManager.Instance.CreateEffect(20);
        goEff.transform.parent = transform;
        goEff.transform.localPosition = EffectManager.Instance.GetPrefab(20).transform.localPosition;
        Destroy(goEff, 5.0f);

        yield return new WaitForSeconds(0.8f);

        goEff.transform.parent = null;

        sprite.color = new Color(1, 1, 1, 0.0f);
        yield return new WaitForSeconds(0.7f);
        Vector3 newPos = mytrans.position;
        newPos.y += 1.6f;
        newPos.z = curBoardTile.transform.position.z - 0.001f;
        //if(tomb==null)
        tomb = Instantiate(BoardManager.Instance.tombPrefab, newPos, Quaternion.identity) as GameObject;
        //else
        //{
        //	tomb.transform.position = newPos;
        //	tomb.SetActive(true);
        //}
		HudManager.Instance.SetRetiredPanelGray(SID,true);
        yield return new WaitForSeconds(1.0f);
        if (isMe)
        {
            /*
            Camera.main.gameObject.GetComponent<GrayscaleEffect>().enabled = true;
            HudManager.Instance.grayEffect.enabled = true;
            yield return new WaitForSeconds(3.0f);
            Camera.main.gameObject.GetComponent<GrayscaleEffect>().enabled = false;
            HudManager.Instance.grayEffect.enabled = false;*/
            UIManager.Instance.ShowRebirthWindow();
        }

        gameObject.SetActive(false);

    }

    public void ShowMPRecoverEffect()
    {
        //HudManager.Instance.ShowAIEmotionChat(SID, "skill_good");
        //HudManager.Instance.ChangeFace(SID, true);

        //		if(manaRecoverEff==null)
        //		{
        //			manaRecoverEff = EffectManager.Instance.CreateEffectParent(24,transform);
        //			manaRecoverEffPS = manaRecoverEff.GetComponent<ParticleSystem>();
        //			manaRecoverEffPS.Play();
        //		}
        //		else
        //			manaRecoverEffPS.Play();

    }

    public bool ChangeBotToPC()
    {
        if (isMe && pawnType == GAME_PAWN_TYPE.BOT)
        {
            CNetworkManager.Instance.SendRequest("wakeup;");
            return true;
        }
        return false;
    }

    public void SetLapCount(int lapcount)
    {
        if (IsPC_or_AI())
        {
            if (BoardManager.Instance.curMapRaceType == RaceType.CURCUIT_RACE)
            {
                Debug.LogError(SID + " set lapcount " + lapcount);
                if (lapcount == 0)
                    isLapCountGoingToZero = true;
                if (m_lapcount != lapcount)
                {
                    isLapChanged = true;
                    StartCoroutine("CoSetLapCount", lapcount);
                }

            }
        }
    }

    IEnumerator CoSetLapCount(int lapcount)
    {
        while (isLapChanged && !curPassingBoard.boardInfo.isStart && m_lapcount != -1)
            yield return null;
        //isLapChanged = false;
        if (m_lapcount != -1 && lapcount < m_lapcount)
        {
            HudManager.Instance.ShowMPChangeEffect_PassingLap();
            /*
            if(!HudManager.Instance.IsMaxMP(SID) )
            {
                HudManager.Instance.IncreaseMainCharMP(SID, 1);
                ShowMPRecoverEffect();
            }*/
            //MainHUDUI.Instance.ChangeMapMarkerByLap(gameOrder, lapcount);
        }
        if (m_lapcount == -1)
        {
            m_lapcount = lapcount;
            MainHUDUI.Instance.MoveMapMarker(gameOrder, curPassingBoard.boardInfo.pathInfo[mypath].ratioToGoal, 0, isBoss, m_lapcount);
        }
        m_lapcount = lapcount;
		glog.debug("set m_lapcount="+m_lapcount, LOGCOLOR.YELLOW);
        HudManager.Instance.SetLapCount(SID, lapcount);

    }

    public void SetGameOrder(int _gameorder)
    {
        gameOrder = _gameorder;
        //if(BoardManager.Instance.curMapRaceType == RaceType.CURCUIT_RACE)
        //	MainHUDUI.Instance.ChangeMapMarkerByLap(gameOrder, m_lapcount);
        //else

        MainHUDUI.Instance.MoveMapMarker(gameOrder, curPassingBoard.boardInfo.pathInfo[mypath].ratioToGoal, 0, isBoss, m_lapcount);
    }

    public void ContunueBattle(byte[] nDiceList, bool isAttackerDiceResult)
    {
        glog.debug("startcoroutine CoContunueBattle " + BoardManager.Instance.isBattleDiceUIDoing);
        StartCoroutine(CoContunueBattle(nDiceList, isAttackerDiceResult));
    }

    IEnumerator CoContunueBattle(byte[] nDiceList, bool isAttackerDiceResult)
    {
        while (BoardManager.Instance.isBattleDiceUIDoing)
            yield return null;
        BoardManager.Instance.ShowDiceUIBattle(this, nDiceList, null, isAttackerDiceResult);
        //if(BoardManager.Instance.curTurnSID == SID)// is attacker
        //	BoardManager.Instance.ShowDiceUIBattle( this, nDiceList, null, true);
        //else
        //	BoardManager.Instance.ShowDiceUIBattle( this, nDiceList, null, false);
    }

    public void MakeShield()
    {
        if (isPushBackResistActivated)
        {
            isPushBackResistActivated = false;
            if (StageManagerWrapper.IsNPCSid(SID))
                return;
            if (shieldPrefab == null)
                shieldPrefab = Resources.Load("Prefabs/Ingame/shield") as GameObject;
            if (shieldPrefab != null)
            {
                if (m_shieldGo == null)
                {
                    Debug.LogError("make shield first");
                    m_shieldGo = Instantiate(shieldPrefab, Vector3.zero, Quaternion.identity) as GameObject;
                }
                if (m_shieldGo != null)
                    ActivateShield();
            }
        }
    }

    void ActivateShield()
    {
        Debug.LogError("ActivateShield");
        m_shieldGo.SetActive(true);
        m_shieldGo.transform.parent = transform;

        SetShieldDir();
    }

    void SetShieldDir()
    {
        tk2dSprite shieldSprite = m_shieldGo.GetComponent<tk2dSprite>();
        string sprName = "shield_front";
        switch (charID)
        {
            case 2:
            case 3:
                {
                    sprName = "shield_A_front";
                }
                break;
            case 4:
            case 6:
            case 82:
                {
                    sprName = "shield_B_front";
                }
                break;
            case 1:
            case 5:
                {
                    sprName = "shield_C_front";
                }
                break;
        }

        bool isBack = false;
        if (moveDir == MoveDir.TopLeft || moveDir == MoveDir.TopRight)
        {
            isBack = true;
            sprName = "shield_back";

            switch (charID)
            {
                case 2:
                case 3:
                    {
                        sprName = "shield_A_back";
                    }
                    break;
                case 4:
                case 6:
                case 82:
                    {
                        sprName = "shield_B_back";
                    }
                    break;
                case 1:
                case 5:
                    {
                        sprName = "shield_C_back";
                    }
                    break;
            }
        }
        shieldSprite.SetSprite(sprName);
        shieldSprite.FlipX = sprite.FlipX;

        Vector3 newPos = Vector3.zero;
        if (isBack)
            newPos.z += 0.0001f;
        else
            newPos.z -= 0.0001f;
        m_shieldGo.transform.localPosition = newPos;
    }

    void CheckShieldDir()
    {
        if (m_shieldGo != null && m_shieldGo.activeSelf)
        {
            SetShieldDir();
        }
    }

    void DeactivateShield()
    {
        if (m_shieldGo != null && m_shieldGo.activeSelf)
        {
            Debug.LogError("DeactivateShield");
            m_shieldGo.SetActive(false);
            m_shieldGo.transform.parent = EffectManager.Instance.transform;
        }

    }

    public void AchieveTempSkill(int skillId)
    {
        if (IsMovingOrWaitMoving() || bMovedToBattlePosition)
        {
            m_achieveTempSkillId = skillId;
        }
        else
            HudManager.Instance.AchieveTempSkill(this, skillId);
    }

    void CheckShowAchieveTempSkill()
    {
        if (m_achieveTempSkillId != 0)
        {
            HudManager.Instance.AchieveTempSkill(this, m_achieveTempSkillId);
            m_achieveTempSkillId = 0;
        }
    }
}
